Compare commits

...

4 Commits

Author SHA1 Message Date
jkunz f0069f87e2 v13.32.0
Docker (tags) / release (push) Failing after 1s
2026-05-19 22:24:40 +00:00
jkunz 77c1738390 feat(ops-auth): add scoped API token auth across ops endpoints 2026-05-19 22:24:37 +00:00
jkunz 53d7c5350e v13.31.0
Docker (tags) / release (push) Failing after 1s
2026-05-19 17:06:52 +00:00
jkunz 7986d01245 feat(opsserver): add admin user create/delete management and default hosted idp.global auth support 2026-05-19 17:06:50 +00:00
57 changed files with 1341 additions and 528 deletions
+21
View File
@@ -5,6 +5,27 @@
## 2026-05-19 - 13.32.0
### Features
- add scoped API token auth across ops endpoints (ops-auth)
- introduces a shared requireOpsAuth helper that validates JWT identities and API tokens with scope and admin-policy checks
- applies explicit per-endpoint authorization across config, logs, stats, security, VPN, RADIUS, remote ingress, users, API tokens, and related ops handlers
- extends request interfaces and UI scope definitions to support apiToken-based access and adds tests for auth behavior and migration bridging
## 2026-05-19 - 13.31.0
### Features
- add admin user create/delete management and default hosted idp.global auth support (opsserver)
- adds admin-only createUser and deleteUser typed requests with safeguards against deleting the current user or last active admin
- updates the ops users UI to create and delete users, show richer account details, and support optional idp.global login during account creation
- treats idp.global as available by default via the hosted https://idp.global endpoint while keeping URL settings as optional overrides
- adds VPN-only route controls and indicators in the ops routes UI
## 2026-05-18 - 13.30.0
### Features
+3 -3
View File
@@ -1,7 +1,7 @@
{
"name": "@serve.zone/dcrouter",
"private": false,
"version": "13.30.0",
"version": "13.32.0",
"description": "A multifaceted routing service handling mail and SMS delivery functions.",
"type": "module",
"exports": {
@@ -38,7 +38,7 @@
"@apiclient.xyz/cloudflare": "^7.1.0",
"@design.estate/dees-catalog": "^3.81.0",
"@design.estate/dees-element": "^2.2.4",
"@idp.global/sdk": "^1.3.0",
"@idp.global/sdk": "^1.3.1",
"@push.rocks/lik": "^6.4.1",
"@push.rocks/projectinfo": "^5.1.0",
"@push.rocks/qenv": "^6.1.4",
@@ -51,7 +51,7 @@
"@push.rocks/smartjwt": "^2.2.2",
"@push.rocks/smartlog": "^3.2.2",
"@push.rocks/smartmetrics": "^3.0.3",
"@push.rocks/smartmigration": "1.3.1",
"@push.rocks/smartmigration": "1.4.1",
"@push.rocks/smartmta": "^5.3.3",
"@push.rocks/smartnetwork": "^4.7.1",
"@push.rocks/smartpath": "^6.0.0",
+10 -10
View File
@@ -30,8 +30,8 @@ importers:
specifier: ^2.2.4
version: 2.2.4
'@idp.global/sdk':
specifier: ^1.3.0
version: 1.3.0(@push.rocks/smartserve@2.0.4)(socks@2.8.8)
specifier: ^1.3.1
version: 1.3.1(@push.rocks/smartserve@2.0.4)(socks@2.8.8)
'@push.rocks/lik':
specifier: ^6.4.1
version: 6.4.1
@@ -69,8 +69,8 @@ importers:
specifier: ^3.0.3
version: 3.0.3
'@push.rocks/smartmigration':
specifier: 1.3.1
version: 1.3.1(@push.rocks/smartbucket@4.6.1)(@push.rocks/smartdata@7.1.7(socks@2.8.8))
specifier: 1.4.1
version: 1.4.1(@push.rocks/smartbucket@4.6.1)(@push.rocks/smartdata@7.1.7(socks@2.8.8))
'@push.rocks/smartmta':
specifier: ^5.3.3
version: 5.3.3
@@ -753,8 +753,8 @@ packages:
'@idp.global/interfaces@1.0.1':
resolution: {integrity: sha512-PEA538+V2VUnKTkLbt66OWxsRZxWHuhC1nduzeFvBaOlH7EIXIZ0rA9D20JKtUZyucZJlXj1hFp2WCMUmgqPwQ==}
'@idp.global/sdk@1.3.0':
resolution: {integrity: sha512-ADxra57bBVHXrsOCrh6c82PhiJoxWZQ9LMPqkfWiQ/jspufo2WhSZIjm7G7C5SvFtGRmiYYJStKfwYBpCKO01w==}
'@idp.global/sdk@1.3.1':
resolution: {integrity: sha512-mZ7cRhbyaE7PoGo9WRJLNwQLIjs9mZxLK1HhVQntvf7hN+OrCRjpYfDn5/G3ub8tpTNq1trtROYNjlhbD/4GLw==}
'@img/colour@1.1.0':
resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==}
@@ -1366,8 +1366,8 @@ packages:
'@push.rocks/smartmetrics@3.0.3':
resolution: {integrity: sha512-RYY4NOla3kraZYVF9TBHgIz4/hSkqVDVNP7tLwhLK5mGBPBy8I/9NWXX6txZKQw6QihP85YD8mWUuUu2xS4D6Q==}
'@push.rocks/smartmigration@1.3.1':
resolution: {integrity: sha512-qU3vc4yCLn8vJQIEMQwS2Lq6Ra8ixSfjutnbR1L/hauCzFRCic3o/DnFKB7pjj5jWaqSDG5nlyeIliLmC5aGsg==}
'@push.rocks/smartmigration@1.4.1':
resolution: {integrity: sha512-kBvWuqBIIgkK2QskjHl0/MPLXYu4CDJDyuPc1KBDPBNejYIJp6hOZtbsmj4DYoNKsgFTpAALJn9JmUEdLe9E4g==}
peerDependencies:
'@push.rocks/smartbucket': ^4.6.1
'@push.rocks/smartdata': ^7.1.7
@@ -5381,7 +5381,7 @@ snapshots:
'@api.global/typedrequest-interfaces': 3.0.19
'@tsclass/tsclass': 9.5.1
'@idp.global/sdk@1.3.0(@push.rocks/smartserve@2.0.4)(socks@2.8.8)':
'@idp.global/sdk@1.3.1(@push.rocks/smartserve@2.0.4)(socks@2.8.8)':
dependencies:
'@api.global/typedrequest': 3.3.1
'@api.global/typedsocket': 4.1.3(@push.rocks/smartserve@2.0.4)
@@ -6508,7 +6508,7 @@ snapshots:
'@push.rocks/smartdelay': 3.1.0
'@push.rocks/smartlog': 3.2.2
'@push.rocks/smartmigration@1.3.1(@push.rocks/smartbucket@4.6.1)(@push.rocks/smartdata@7.1.7(socks@2.8.8))':
'@push.rocks/smartmigration@1.4.1(@push.rocks/smartbucket@4.6.1)(@push.rocks/smartdata@7.1.7(socks@2.8.8))':
dependencies:
'@push.rocks/smartlog': 3.2.2
'@push.rocks/smartversion': 3.1.0
+1 -1
View File
@@ -86,7 +86,7 @@ Bootstrap behavior:
- `getAdminBootstrapStatus` reports whether persistence is ready and whether a first admin is required.
- The temporary env/config admin identity is only used to authorize bootstrap access while no persisted admin exists.
- `createInitialAdminUser` creates the first persisted admin with normalized email and local password authentication.
- Optional `idp.global` authentication can be enabled for that local account; the local dcrouter role remains authoritative and the IdP email must match the local account email.
- Optional `idp.global` authentication can be enabled for that local account. The hosted `https://idp.global` endpoint is used by default, `adminAuth.idpGlobalUrl` or `DCROUTER_IDP_GLOBAL_URL` only override it, and the local dcrouter role remains authoritative.
- After a persisted admin exists, temporary bootstrap admin login is rejected and normal persisted-account authentication is used.
## Configuration Model
+41
View File
@@ -16,6 +16,7 @@ let testDb: DcRouterDb;
let storagePath: string;
let bootstrapIdentity: interfaces.data.IIdentity;
let persistedIdentity: interfaces.data.IIdentity;
let createdUserId: string;
const createStatusRequest = () => new TypedRequest<interfaces.requests.IReq_GetAdminBootstrapStatus>(
baseUrl,
@@ -84,6 +85,7 @@ tap.test('reports bootstrap required without auto-persisting an admin', async ()
expect(status.hasPersistentAdmin).toEqual(false);
expect(status.needsBootstrap).toEqual(true);
expect(status.ephemeralAdminAvailable).toEqual(true);
expect(status.idpGlobalConfigured).toEqual(true);
});
tap.test('allows temporary bootstrap admin login before persisted admin exists', async () => {
@@ -183,6 +185,45 @@ tap.test('rejects idp.global login when IdP email does not match local account',
expect(rejected).toEqual(true);
});
tap.test('creates a persisted non-admin user explicitly', async () => {
const request = new TypedRequest<interfaces.requests.IReq_CreateUser>(baseUrl, 'createUser');
const response = await request.fire({
identity: persistedIdentity,
email: 'operator@example.com',
name: 'Operator User',
role: 'user',
password: 'operator-password',
});
expect(response.success).toEqual(true);
expect(response.user?.role).toEqual('user');
expect(response.user?.email).toEqual('operator@example.com');
if (!response.user?.id) {
throw new Error('Expected created user id');
}
createdUserId = response.user.id;
});
tap.test('rejects deleting the current persisted admin user', async () => {
const request = new TypedRequest<interfaces.requests.IReq_DeleteUser>(baseUrl, 'deleteUser');
const response = await request.fire({
identity: persistedIdentity,
id: persistedIdentity.userId,
});
expect(response.success).toEqual(false);
});
tap.test('deletes a persisted non-current user', async () => {
const request = new TypedRequest<interfaces.requests.IReq_DeleteUser>(baseUrl, 'deleteUser');
const response = await request.fire({
identity: persistedIdentity,
id: createdUserId,
});
expect(response.success).toEqual(true);
});
tap.test('lists persisted users without password material', async () => {
const request = new TypedRequest<interfaces.requests.IReq_ListUsers>(baseUrl, 'listUsers');
const response = await request.fire({ identity: persistedIdentity });
+1
View File
@@ -56,6 +56,7 @@ const setupHandler = (scopes: TScope[], options?: {
const opsServerRef: any = {
typedrouter,
adminHandler: {
validateIdentity: async () => null,
adminIdentityGuard: {
exec: async () => false,
},
+79
View File
@@ -0,0 +1,79 @@
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { ConfigHandler } from '../ts/opsserver/handlers/config.handler.js';
import * as plugins from '../ts/plugins.js';
import * as interfaces from '../ts_interfaces/index.js';
const fireTypedRequest = async (
router: plugins.typedrequest.TypedRouter,
method: string,
request: Record<string, any>,
) => {
return await router.routeAndAddResponse({
method,
request,
response: {},
correlation: {
id: `${method}-${Date.now()}-${Math.random().toString(16).slice(2)}`,
phase: 'request',
},
} as any, { localRequest: true, skipHooks: true }) as any;
};
const makeOpsServer = (scopes: interfaces.data.TApiTokenScope[]) => {
const router = new plugins.typedrequest.TypedRouter();
const token = {
id: 'token-1',
name: 'config-token',
tokenHash: 'hash',
scopes,
createdBy: 'token-user',
createdAt: Date.now(),
expiresAt: null,
lastUsedAt: null,
enabled: true,
} as interfaces.data.IStoredApiToken;
const opsServerRef = {
viewRouter: router,
adminHandler: {
validateIdentity: async () => null,
},
dcRouterRef: {
options: {
dbConfig: { enabled: false },
},
resolvedPaths: {
dcrouterHomeDir: '/tmp/dcrouter-home',
dataDir: '/tmp/dcrouter-data',
defaultTsmDbPath: '/tmp/dcrouter-data/db',
},
detectedPublicIp: null,
apiTokenManager: {
validateToken: async (rawTokenArg: string) => rawTokenArg === 'valid-token' ? token : null,
hasScope: (storedTokenArg: interfaces.data.IStoredApiToken, scopeArg: interfaces.data.TApiTokenScope) => storedTokenArg.scopes.includes(scopeArg),
},
},
} as any;
new ConfigHandler(opsServerRef);
return router;
};
tap.test('ConfigHandler accepts API token with config:read', async () => {
const router = makeOpsServer(['config:read']);
const result = await fireTypedRequest(router, 'getConfiguration', {
apiToken: 'valid-token',
});
expect(result.error).toBeUndefined();
expect(result.response.config.system.baseDir).toEqual('/tmp/dcrouter-home');
});
tap.test('ConfigHandler rejects API token without config:read', async () => {
const router = makeOpsServer(['logs:read']);
const result = await fireTypedRequest(router, 'getConfiguration', {
apiToken: 'valid-token',
});
expect(result.error?.text).toEqual('insufficient scope');
});
export default tap.start();
+69
View File
@@ -0,0 +1,69 @@
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { createMigrationRunner } from '../ts_migrations/index.js';
function setPath(target: Record<string, any>, path: string, value: unknown): void {
const parts = path.split('.');
let cursor = target;
for (const part of parts.slice(0, -1)) {
cursor[part] = cursor[part] || {};
cursor = cursor[part];
}
cursor[parts[parts.length - 1]] = value;
}
function applySet(document: Record<string, any>, set: Record<string, unknown>): void {
for (const [key, value] of Object.entries(set)) {
setPath(document, key, value);
}
}
function createFakeDb(currentVersion: string) {
const ledgerDocument = {
nameId: 'smartmigration:smartmigration',
data: {
currentVersion,
steps: {},
lock: { holder: null, acquiredAt: null, expiresAt: null },
checkpoints: {},
},
};
const emptyCollection = {
find: () => ({
async *[Symbol.asyncIterator]() {},
}),
updateMany: async () => ({ modifiedCount: 0 }),
};
const ledgerCollection = {
createIndex: async () => undefined,
findOne: async () => structuredClone(ledgerDocument),
findOneAndUpdate: async (_query: unknown, update: any) => {
applySet(ledgerDocument, update.$set || {});
return structuredClone(ledgerDocument);
},
updateOne: async (_query: unknown, update: any) => {
applySet(ledgerDocument, update.$set || {});
return { matchedCount: 1, modifiedCount: 1, upsertedCount: 0 };
},
};
return {
mongoDb: {
collection: (name: string) =>
name === 'SmartdataEasyStore' ? ledgerCollection : emptyCollection,
},
};
}
tap.test('migration runner bridges old package-version targets without real schema steps', async () => {
const runner = await createMigrationRunner(createFakeDb('13.16.0'), '13.31.0');
const result = await runner.run();
expect(result.currentVersionBefore).toEqual('13.16.0');
expect(result.currentVersionAfter).toEqual('13.31.0');
expect(result.stepsApplied).toHaveLength(3);
});
export default tap.start();
+126
View File
@@ -0,0 +1,126 @@
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { requireOpsAuth } from '../ts/opsserver/helpers/auth.js';
import * as interfaces from '../ts_interfaces/index.js';
type TScope = interfaces.data.TApiTokenScope;
const makeIdentity = (role: string = 'user'): interfaces.data.IIdentity => ({
jwt: `jwt-${role}`,
userId: `${role}-user`,
name: role,
expiresAt: Date.now() + 3600000,
role,
});
const makeOpsServer = (options: {
identityRole?: string | null;
tokenScopes?: TScope[];
tokenPolicy?: interfaces.data.IApiTokenPolicy;
}) => {
const token = {
id: 'token-1',
name: 'test-token',
tokenHash: 'hash',
scopes: options.tokenScopes || [],
policy: options.tokenPolicy,
createdAt: Date.now(),
expiresAt: null,
lastUsedAt: null,
createdBy: 'token-user',
enabled: true,
} as interfaces.data.IStoredApiToken;
return {
adminHandler: {
validateIdentity: async (identityArg?: interfaces.data.IIdentity) => {
if (!identityArg || options.identityRole === null) return null;
return { ...identityArg, role: options.identityRole || identityArg.role || 'user' };
},
},
dcRouterRef: {
apiTokenManager: {
validateToken: async (rawTokenArg: string) => rawTokenArg === 'valid-token' ? token : null,
hasScope: (storedTokenArg: interfaces.data.IStoredApiToken, scopeArg: TScope) => {
if (storedTokenArg.policy?.role === 'admin') return true;
return storedTokenArg.scopes.includes('*') || storedTokenArg.scopes.includes(scopeArg) || Boolean(storedTokenArg.policy?.scopes?.includes(scopeArg));
},
},
},
} as any;
};
const getErrorText = (errorArg: unknown) => {
return (errorArg as any).errorText || (errorArg as any).text || (errorArg as Error).message;
};
tap.test('requireOpsAuth accepts valid JWT identity for read endpoints', async () => {
const auth = await requireOpsAuth(
makeOpsServer({ identityRole: 'user' }),
{ identity: makeIdentity('user') },
{ scope: 'config:read' },
);
expect(auth.type).toEqual('identity');
expect(auth.userId).toEqual('user-user');
expect(auth.isAdmin).toEqual(false);
});
tap.test('requireOpsAuth rejects non-admin JWT identity for admin identity requirements', async () => {
let errorText = '';
try {
await requireOpsAuth(
makeOpsServer({ identityRole: 'user' }),
{ identity: makeIdentity('user') },
{ scope: 'routes:write', requireAdminIdentity: true },
);
} catch (error) {
errorText = getErrorText(error);
}
expect(errorText).toEqual('admin identity required');
});
tap.test('requireOpsAuth accepts scoped API tokens', async () => {
const auth = await requireOpsAuth(
makeOpsServer({ identityRole: null, tokenScopes: ['logs:read'] }),
{ apiToken: 'valid-token' },
{ scope: 'logs:read' },
);
expect(auth.type).toEqual('apiToken');
expect(auth.userId).toEqual('token-user');
});
tap.test('requireOpsAuth rejects API tokens without the required scope', async () => {
let errorText = '';
try {
await requireOpsAuth(
makeOpsServer({ identityRole: null, tokenScopes: ['logs:read'] }),
{ apiToken: 'valid-token' },
{ scope: 'stats:read' },
);
} catch (error) {
errorText = getErrorText(error);
}
expect(errorText).toEqual('insufficient scope');
});
tap.test('requireOpsAuth requires admin policy for sensitive API-token operations', async () => {
let errorText = '';
try {
await requireOpsAuth(
makeOpsServer({ identityRole: null, tokenScopes: ['tokens:manage'] }),
{ apiToken: 'valid-token' },
{ scope: 'tokens:manage', requireAdminToken: true },
);
} catch (error) {
errorText = getErrorText(error);
}
expect(errorText).toEqual('admin API token required');
const auth = await requireOpsAuth(
makeOpsServer({ identityRole: null, tokenPolicy: { role: 'admin' } }),
{ apiToken: 'valid-token' },
{ scope: 'tokens:manage', requireAdminToken: true },
);
expect(auth.isAdmin).toEqual(true);
});
export default tap.start();
+3
View File
@@ -136,6 +136,9 @@ const setupHandler = (options: {
const opsServerRef: any = {
typedrouter,
adminHandler: {
validateIdentity: async (identity: interfaces.data.IIdentity) => options.isAdmin
? { ...identity, role: 'admin' }
: identity,
adminIdentityGuard: {
exec: async () => Boolean(options.isAdmin),
},
+1 -1
View File
@@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@serve.zone/dcrouter',
version: '13.30.0',
version: '13.32.0',
description: 'A multifaceted routing service handling mail and SMS delivery functions.'
}
+1 -1
View File
@@ -169,7 +169,7 @@ export interface IDcRouterOptions {
/** Optional OpsServer account authentication settings. */
adminAuth?: {
/** Base URL for idp.global password authentication. Can also be set through DCROUTER_IDP_GLOBAL_URL. */
/** Optional idp.global password-authentication URL override. Defaults to the SDK's hosted https://idp.global endpoint. Can also be set through DCROUTER_IDP_GLOBAL_URL. */
idpGlobalUrl?: string;
/** Test/integration hook for injecting an idp.global-compatible password client. */
idpClient?: Pick<plugins.idpSdkServer.IdpGlobalServerClient, 'loginWithEmailAndPassword' | 'stop'>;
+3 -14
View File
@@ -3,7 +3,6 @@ import * as plugins from '../plugins.js';
import * as paths from '../paths.js';
import * as handlers from './handlers/index.js';
import * as interfaces from '../../ts_interfaces/index.js';
import { requireValidIdentity, requireAdminIdentity } from './helpers/guards.js';
export class OpsServer {
public dcRouterRef: DcRouter;
@@ -12,9 +11,9 @@ export class OpsServer {
// Main TypedRouter — unauthenticated endpoints (login/logout/verify) and own-auth handlers
public typedrouter = new plugins.typedrequest.TypedRouter();
// Auth-enforced routers — middleware validates identity before any handler runs
public viewRouter = new plugins.typedrequest.TypedRouter<{ request: { identity: interfaces.data.IIdentity } }>();
public adminRouter = new plugins.typedrequest.TypedRouter<{ request: { identity: interfaces.data.IIdentity } }>();
// Grouped routers. Handlers enforce auth explicitly with per-endpoint scopes.
public viewRouter = new plugins.typedrequest.TypedRouter<{ request: { identity?: interfaces.data.IIdentity; apiToken?: string } }>();
public adminRouter = new plugins.typedrequest.TypedRouter<{ request: { identity?: interfaces.data.IIdentity; apiToken?: string } }>();
// Handler instances
public adminHandler!: handlers.AdminHandler;
@@ -72,16 +71,6 @@ export class OpsServer {
this.adminHandler = new handlers.AdminHandler(this);
await this.adminHandler.initialize();
// viewRouter middleware: requires valid identity (any logged-in user)
this.viewRouter.addMiddleware(async (typedRequest) => {
await requireValidIdentity(this.adminHandler, typedRequest.request);
});
// adminRouter middleware: requires admin identity
this.adminRouter.addMiddleware(async (typedRequest) => {
await requireAdminIdentity(this.adminHandler, typedRequest.request);
});
// Connect auth routers to the main typedrouter
this.typedrouter.addTypedRouter(this.viewRouter);
this.typedrouter.addTypedRouter(this.adminRouter);
+6 -23
View File
@@ -1,6 +1,7 @@
import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
import { requireOpsAuth } from '../helpers/auth.js';
/**
* CRUD handler for the singleton `AcmeConfigDoc`.
@@ -20,29 +21,11 @@ export class AcmeConfigHandler {
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');
const auth = await requireOpsAuth(this.opsServerRef, request, {
scope: requiredScope,
requireAdminIdentity: requiredScope?.endsWith(':write'),
});
return auth.userId;
}
private registerHandlers(): void {
+155 -111
View File
@@ -159,6 +159,93 @@ export class AdminHandler {
throw new plugins.typedrequest.TypedResponseError((error as Error).message || 'failed to create initial admin');
}
}
public async createUser(optionsArg: {
email: string;
name?: string;
role: interfaces.requests.TUserManagementRole;
password: string;
enableIdpGlobalAuth?: boolean;
}): Promise<interfaces.requests.IReq_CreateUser['response']> {
const store = this.getAccountStore();
if (!store) {
return { success: false, message: 'database is not ready' };
}
if (!(await store.hasActiveAdminAccount())) {
return { success: false, message: 'initial admin bootstrap is required before creating users' };
}
const role = optionsArg.role;
if (role !== 'admin' && role !== 'user') {
return { success: false, message: 'role must be admin or user' };
}
const password = String(optionsArg.password || '');
if (!password) {
return { success: false, message: 'password is required' };
}
const authSources: Array<'local' | 'idp.global'> = ['local'];
if (optionsArg.enableIdpGlobalAuth) {
authSources.push('idp.global');
}
try {
const email = String(optionsArg.email || '').trim();
const account = await store.createAccount({
email,
name: String(optionsArg.name || '').trim() || email,
role,
authSources,
password,
});
return { success: true, user: this.accountToUser(account) };
} catch (error) {
return { success: false, message: (error as Error).message || 'failed to create user' };
}
}
public async deleteUser(optionsArg: {
id: string;
requestingUserId: string;
}): Promise<interfaces.requests.IReq_DeleteUser['response']> {
const store = this.getAccountStore();
if (!store) {
return { success: false, message: 'database is not ready' };
}
if (!(await store.hasActiveAdminAccount())) {
return { success: false, message: 'initial admin bootstrap is required before deleting users' };
}
const id = String(optionsArg.id || '').trim();
if (!id) {
return { success: false, message: 'user id is required' };
}
if (id === optionsArg.requestingUserId) {
return { success: false, message: 'cannot delete the current user' };
}
const account = await store.getAccountById(id);
if (!account) {
return { success: false, message: 'user not found' };
}
if (account.role === 'admin' && account.status === 'active') {
const activeAdmins = (await store.listAccounts()).filter(
(accountArg) => accountArg.role === 'admin' && accountArg.status === 'active',
);
if (activeAdmins.length <= 1) {
return { success: false, message: 'cannot delete the last active admin' };
}
}
const doc = await plugins.idpSdkServer.IdpSdkAccountDoc.findById(id);
if (!doc) {
return { success: false, message: 'user not found' };
}
await doc.delete();
return { success: true };
}
private registerHandlers(): void {
this.typedrouter.addTypedHandler(
@@ -171,12 +258,18 @@ export class AdminHandler {
this.opsServerRef.adminRouter.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_CreateInitialAdminUser>(
'createInitialAdminUser',
async (dataArg) => this.createInitialAdminUser({
email: dataArg.email,
name: dataArg.name,
password: dataArg.password,
enableIdpGlobalAuth: dataArg.enableIdpGlobalAuth,
})
async (dataArg) => {
const isAdmin = await this.adminIdentityGuard.exec({ identity: dataArg.identity });
if (!isAdmin) {
throw new plugins.typedrequest.TypedResponseError('admin identity required');
}
return this.createInitialAdminUser({
email: dataArg.email,
name: dataArg.name,
password: dataArg.password,
enableIdpGlobalAuth: dataArg.enableIdpGlobalAuth,
});
}
)
);
@@ -213,8 +306,10 @@ export class AdminHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_AdminLogout>(
'adminLogout',
async (dataArg) => {
// In a real implementation, you might want to blacklist the JWT
// For now, just return success
const identity = await this.validateIdentity(dataArg.identity);
if (!identity) {
throw new plugins.typedrequest.TypedResponseError('identity is not valid');
}
return {
success: true,
};
@@ -227,52 +322,8 @@ export class AdminHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_VerifyIdentity>(
'verifyIdentity',
async (dataArg) => {
if (!dataArg.identity?.jwt) {
return {
valid: false,
};
}
try {
const jwtData = await this.smartjwtInstance.verifyJWTAndGetData(dataArg.identity.jwt);
// Check if expired
if (jwtData.expiresAt < Date.now()) {
return {
valid: false,
};
}
// Check if logged in
if (jwtData.status !== 'loggedIn') {
return {
valid: false,
};
}
const user = await this.resolveUser(jwtData.userId);
if (!user) {
return {
valid: false,
};
}
return {
valid: true,
identity: {
jwt: dataArg.identity.jwt,
userId: user.id,
name: user.name || user.username,
expiresAt: jwtData.expiresAt,
role: user.role,
type: 'user',
},
};
} catch (error) {
return {
valid: false,
};
}
const identity = await this.validateIdentity(dataArg.identity);
return identity ? { valid: true, identity } : { valid: false };
}
)
);
@@ -285,45 +336,7 @@ export class AdminHandler {
identity: interfaces.data.IIdentity;
}>(
async (dataArg) => {
if (!dataArg.identity?.jwt) {
return false;
}
try {
const jwtData = await this.smartjwtInstance.verifyJWTAndGetData(dataArg.identity.jwt);
// Check expiration
if (jwtData.expiresAt < Date.now()) {
return false;
}
// Check status
if (jwtData.status !== 'loggedIn') {
return false;
}
// Verify data hasn't been tampered with
if (dataArg.identity.expiresAt !== jwtData.expiresAt) {
return false;
}
if (dataArg.identity.userId !== jwtData.userId) {
return false;
}
const user = await this.resolveUser(jwtData.userId);
if (!user) {
return false;
}
if (dataArg.identity.role && dataArg.identity.role !== user.role) {
return false;
}
return true;
} catch (error) {
return false;
}
return Boolean(await this.validateIdentity(dataArg.identity));
},
{
failedHint: 'identity is not valid',
@@ -338,14 +351,8 @@ export class AdminHandler {
identity: interfaces.data.IIdentity;
}>(
async (dataArg) => {
// First check if identity is valid
const isValid = await this.validIdentityGuard.exec(dataArg);
if (!isValid) {
return false;
}
// Check if user has admin role
return dataArg.identity.role === 'admin';
const identity = await this.validateIdentity(dataArg.identity);
return identity?.role === 'admin';
},
{
failedHint: 'user is not admin',
@@ -353,6 +360,49 @@ export class AdminHandler {
}
);
public async validateIdentity(
identityArg?: interfaces.data.IIdentity,
): Promise<interfaces.data.IIdentity | null> {
if (!identityArg?.jwt) {
return null;
}
try {
const jwtData = await this.smartjwtInstance.verifyJWTAndGetData(identityArg.jwt);
if (jwtData.expiresAt < Date.now()) {
return null;
}
if (jwtData.status !== 'loggedIn') {
return null;
}
if (identityArg.expiresAt !== jwtData.expiresAt) {
return null;
}
if (identityArg.userId !== jwtData.userId) {
return null;
}
const user = await this.resolveUser(jwtData.userId);
if (!user) {
return null;
}
if (identityArg.role && identityArg.role !== user.role) {
return null;
}
return {
jwt: identityArg.jwt,
userId: user.id,
name: user.name || user.username,
expiresAt: jwtData.expiresAt,
role: user.role,
type: 'user',
};
} catch {
return null;
}
}
private async authenticateUser(optionsArg: {
username: string;
password: string;
@@ -420,23 +470,17 @@ export class AdminHandler {
}
const baseUrl = this.opsServerRef.dcRouterRef.options.adminAuth?.idpGlobalUrl || process.env.DCROUTER_IDP_GLOBAL_URL;
if (!baseUrl) {
return undefined;
}
if (!this.idpClient) {
this.idpClient = new plugins.idpSdkServer.IdpGlobalServerClient({ baseUrl });
this.idpClient = baseUrl
? new plugins.idpSdkServer.IdpGlobalServerClient({ baseUrl })
: new plugins.idpSdkServer.IdpGlobalServerClient({} as plugins.idpSdkServer.IIdpGlobalServerClientOptions);
this.ownsIdpClient = true;
}
return this.idpClient;
}
private isIdpGlobalConfigured(): boolean {
return !!(
this.opsServerRef.dcRouterRef.options.adminAuth?.idpClient ||
this.opsServerRef.dcRouterRef.options.adminAuth?.idpGlobalUrl ||
process.env.DCROUTER_IDP_GLOBAL_URL
);
return true;
}
private accountToUser(accountArg: plugins.idpSdkServer.IIdpSdkAccount): TAdminUser {
+27 -1
View File
@@ -1,6 +1,7 @@
import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
import { requireOpsAuth } from '../helpers/auth.js';
export class ApiTokenHandler {
constructor(private opsServerRef: OpsServer) {
@@ -17,6 +18,11 @@ export class ApiTokenHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_CreateApiToken>(
'createApiToken',
async (dataArg) => {
const auth = await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'tokens:manage',
requireAdminIdentity: true,
requireAdminToken: true,
});
const manager = this.opsServerRef.dcRouterRef.apiTokenManager;
if (!manager) {
return { success: false, message: 'Token management not initialized' };
@@ -25,7 +31,7 @@ export class ApiTokenHandler {
dataArg.name,
dataArg.scopes,
dataArg.expiresInDays ?? null,
dataArg.identity.userId,
auth.userId,
dataArg.policy,
);
return { success: true, tokenId: result.id, tokenValue: result.rawToken };
@@ -38,6 +44,11 @@ export class ApiTokenHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_ListApiTokens>(
'listApiTokens',
async (dataArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'tokens:read',
requireAdminIdentity: true,
requireAdminToken: true,
});
const manager = this.opsServerRef.dcRouterRef.apiTokenManager;
if (!manager) {
return { tokens: [] };
@@ -52,6 +63,11 @@ export class ApiTokenHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_RevokeApiToken>(
'revokeApiToken',
async (dataArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'tokens:manage',
requireAdminIdentity: true,
requireAdminToken: true,
});
const manager = this.opsServerRef.dcRouterRef.apiTokenManager;
if (!manager) {
return { success: false, message: 'Token management not initialized' };
@@ -67,6 +83,11 @@ export class ApiTokenHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_RollApiToken>(
'rollApiToken',
async (dataArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'tokens:manage',
requireAdminIdentity: true,
requireAdminToken: true,
});
const manager = this.opsServerRef.dcRouterRef.apiTokenManager;
if (!manager) {
return { success: false, message: 'Token management not initialized' };
@@ -85,6 +106,11 @@ export class ApiTokenHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_ToggleApiToken>(
'toggleApiToken',
async (dataArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'tokens:manage',
requireAdminIdentity: true,
requireAdminToken: true,
});
const manager = this.opsServerRef.dcRouterRef.apiTokenManager;
if (!manager) {
return { success: false, message: 'Token management not initialized' };
+6 -23
View File
@@ -3,6 +3,7 @@ import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
import { AcmeCertDoc, ProxyCertDoc } from '../../db/index.js';
import { logger } from '../../logger.js';
import { requireOpsAuth } from '../helpers/auth.js';
/**
* Mirrors `SmartacmeCertMatcher.getCertificateDomainNameByDomainName` from
@@ -37,29 +38,11 @@ export class CertificateHandler {
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');
const auth = await requireOpsAuth(this.opsServerRef, request, {
scope: requiredScope,
requireAdminIdentity: requiredScope?.endsWith(':write'),
});
return auth.userId;
}
private registerHandlers(): void {
+2
View File
@@ -2,6 +2,7 @@ import * as plugins from '../../plugins.js';
import * as paths from '../../paths.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
import { requireOpsAuth } from '../helpers/auth.js';
export class ConfigHandler {
constructor(private opsServerRef: OpsServer) {
@@ -17,6 +18,7 @@ export class ConfigHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetConfiguration>(
'getConfiguration',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'config:read' });
const config = await this.getConfiguration();
return {
config,
+6 -23
View File
@@ -1,6 +1,7 @@
import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
import { requireOpsAuth } from '../helpers/auth.js';
/**
* CRUD + connection-test handlers for DnsProviderDoc.
@@ -20,29 +21,11 @@ export class DnsProviderHandler {
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');
const auth = await requireOpsAuth(this.opsServerRef, request, {
scope: requiredScope,
requireAdminIdentity: requiredScope?.endsWith(':write'),
});
return auth.userId;
}
private registerHandlers(): void {
+6 -23
View File
@@ -1,6 +1,7 @@
import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
import { requireOpsAuth } from '../helpers/auth.js';
/**
* CRUD handlers for DnsRecordDoc.
@@ -17,29 +18,11 @@ export class DnsRecordHandler {
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');
const auth = await requireOpsAuth(this.opsServerRef, request, {
scope: requiredScope,
requireAdminIdentity: requiredScope?.endsWith(':write'),
});
return auth.userId;
}
private registerHandlers(): void {
+6 -23
View File
@@ -1,6 +1,7 @@
import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
import { requireOpsAuth } from '../helpers/auth.js';
/**
* CRUD handlers for DomainDoc.
@@ -17,29 +18,11 @@ export class DomainHandler {
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');
const auth = await requireOpsAuth(this.opsServerRef, request, {
scope: requiredScope,
requireAdminIdentity: requiredScope?.endsWith(':write'),
});
return auth.userId;
}
private registerHandlers(): void {
+6 -23
View File
@@ -1,6 +1,7 @@
import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
import { requireOpsAuth } from '../helpers/auth.js';
/**
* CRUD + DNS provisioning handler for email domains.
@@ -19,29 +20,11 @@ export class EmailDomainHandler {
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');
const auth = await requireOpsAuth(this.opsServerRef, request, {
scope: requiredScope,
requireAdminIdentity: requiredScope?.endsWith(':write'),
});
return auth.userId;
}
private get manager() {
@@ -1,6 +1,7 @@
import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
import { requireOpsAuth } from '../helpers/auth.js';
export class EmailOpsHandler {
constructor(private opsServerRef: OpsServer) {
@@ -18,6 +19,7 @@ export class EmailOpsHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetAllEmails>(
'getAllEmails',
async (dataArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'emails:read' });
const emails = this.getAllQueueEmails();
return { emails };
}
@@ -29,6 +31,7 @@ export class EmailOpsHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetEmailDetail>(
'getEmailDetail',
async (dataArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'emails:read' });
const email = this.getEmailDetail(dataArg.emailId);
return { email };
}
@@ -42,6 +45,10 @@ export class EmailOpsHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_ResendEmail>(
'resendEmail',
async (dataArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'emails:write',
requireAdminIdentity: true,
});
const emailServer = this.opsServerRef.dcRouterRef.emailServer;
if (!emailServer?.deliveryQueue) {
return { success: false, error: 'Email server not available' };
+3
View File
@@ -2,6 +2,7 @@ import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
import { logBuffer, baseLogger } from '../../logger.js';
import { requireOpsAuth } from '../helpers/auth.js';
// Module-level singleton: the log push destination is added once and reuses
// the current OpsServer reference so it survives OpsServer restarts without
@@ -40,6 +41,7 @@ export class LogsHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetRecentLogs>(
'getRecentLogs',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'logs:read' });
const logs = await this.getRecentLogs(
dataArg.level,
dataArg.category,
@@ -63,6 +65,7 @@ export class LogsHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetLogStream>(
'getLogStream',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'logs:read' });
// Create a virtual stream for log streaming
const virtualStream = new plugins.typedrequest.VirtualStream<Uint8Array>();
@@ -1,6 +1,7 @@
import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
import { requireOpsAuth } from '../helpers/auth.js';
export class NetworkTargetHandler {
public typedrouter = new plugins.typedrequest.TypedRouter();
@@ -14,29 +15,11 @@ export class NetworkTargetHandler {
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');
const auth = await requireOpsAuth(this.opsServerRef, request, {
scope: requiredScope,
requireAdminIdentity: requiredScope?.endsWith(':write'),
});
return auth.userId;
}
private registerHandlers(): void {
+31
View File
@@ -1,6 +1,7 @@
import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
import { requireOpsAuth } from '../helpers/auth.js';
export class RadiusHandler {
constructor(private opsServerRef: OpsServer) {
@@ -19,6 +20,7 @@ export class RadiusHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetRadiusClients>(
'getRadiusClients',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'radius:read' });
const radiusServer = this.opsServerRef.dcRouterRef.radiusServer;
if (!radiusServer) {
@@ -43,6 +45,10 @@ export class RadiusHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_SetRadiusClient>(
'setRadiusClient',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'radius:write',
requireAdminIdentity: true,
});
const radiusServer = this.opsServerRef.dcRouterRef.radiusServer;
if (!radiusServer) {
@@ -64,6 +70,10 @@ export class RadiusHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_RemoveRadiusClient>(
'removeRadiusClient',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'radius:write',
requireAdminIdentity: true,
});
const radiusServer = this.opsServerRef.dcRouterRef.radiusServer;
if (!radiusServer) {
@@ -88,6 +98,7 @@ export class RadiusHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetVlanMappings>(
'getVlanMappings',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'radius:read' });
const radiusServer = this.opsServerRef.dcRouterRef.radiusServer;
if (!radiusServer) {
@@ -124,6 +135,10 @@ export class RadiusHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_SetVlanMapping>(
'setVlanMapping',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'radius:write',
requireAdminIdentity: true,
});
const radiusServer = this.opsServerRef.dcRouterRef.radiusServer;
if (!radiusServer) {
@@ -156,6 +171,10 @@ export class RadiusHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_RemoveVlanMapping>(
'removeVlanMapping',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'radius:write',
requireAdminIdentity: true,
});
const radiusServer = this.opsServerRef.dcRouterRef.radiusServer;
if (!radiusServer) {
@@ -177,6 +196,10 @@ export class RadiusHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_UpdateVlanConfig>(
'updateVlanConfig',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'radius:write',
requireAdminIdentity: true,
});
const radiusServer = this.opsServerRef.dcRouterRef.radiusServer;
if (!radiusServer) {
@@ -209,6 +232,7 @@ export class RadiusHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_TestVlanAssignment>(
'testVlanAssignment',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'radius:read' });
const radiusServer = this.opsServerRef.dcRouterRef.radiusServer;
if (!radiusServer) {
@@ -243,6 +267,7 @@ export class RadiusHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetRadiusSessions>(
'getRadiusSessions',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'radius:read' });
const radiusServer = this.opsServerRef.dcRouterRef.radiusServer;
if (!radiusServer) {
@@ -292,6 +317,10 @@ export class RadiusHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DisconnectRadiusSession>(
'disconnectRadiusSession',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'radius:write',
requireAdminIdentity: true,
});
const radiusServer = this.opsServerRef.dcRouterRef.radiusServer;
if (!radiusServer) {
@@ -317,6 +346,7 @@ export class RadiusHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetRadiusAccountingSummary>(
'getRadiusAccountingSummary',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'radius:read' });
const radiusServer = this.opsServerRef.dcRouterRef.radiusServer;
if (!radiusServer) {
@@ -354,6 +384,7 @@ export class RadiusHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetRadiusStatistics>(
'getRadiusStatistics',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'radius:read' });
const radiusServer = this.opsServerRef.dcRouterRef.radiusServer;
if (!radiusServer) {
@@ -1,6 +1,7 @@
import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
import { requireOpsAuth } from '../helpers/auth.js';
export class RemoteIngressHandler {
constructor(private opsServerRef: OpsServer) {
@@ -18,6 +19,7 @@ export class RemoteIngressHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetRemoteIngresses>(
'getRemoteIngresses',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'remote-ingress:read' });
const manager = this.opsServerRef.dcRouterRef.remoteIngressManager;
if (!manager) {
return { edges: [] };
@@ -46,6 +48,10 @@ export class RemoteIngressHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_CreateRemoteIngress>(
'createRemoteIngress',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'remote-ingress:write',
requireAdminIdentity: true,
});
const manager = this.opsServerRef.dcRouterRef.remoteIngressManager;
const tunnelManager = this.opsServerRef.dcRouterRef.tunnelManager;
@@ -78,6 +84,10 @@ export class RemoteIngressHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DeleteRemoteIngress>(
'deleteRemoteIngress',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'remote-ingress:write',
requireAdminIdentity: true,
});
const manager = this.opsServerRef.dcRouterRef.remoteIngressManager;
const tunnelManager = this.opsServerRef.dcRouterRef.tunnelManager;
@@ -103,6 +113,10 @@ export class RemoteIngressHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_UpdateRemoteIngress>(
'updateRemoteIngress',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'remote-ingress:write',
requireAdminIdentity: true,
});
const manager = this.opsServerRef.dcRouterRef.remoteIngressManager;
const tunnelManager = this.opsServerRef.dcRouterRef.tunnelManager;
@@ -148,6 +162,10 @@ export class RemoteIngressHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_RegenerateRemoteIngressSecret>(
'regenerateRemoteIngressSecret',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'remote-ingress:write',
requireAdminIdentity: true,
});
const manager = this.opsServerRef.dcRouterRef.remoteIngressManager;
const tunnelManager = this.opsServerRef.dcRouterRef.tunnelManager;
@@ -175,6 +193,7 @@ export class RemoteIngressHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetRemoteIngressStatus>(
'getRemoteIngressStatus',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'remote-ingress:read' });
const tunnelManager = this.opsServerRef.dcRouterRef.tunnelManager;
if (!tunnelManager) {
return { statuses: [] };
@@ -189,6 +208,10 @@ export class RemoteIngressHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetRemoteIngressConnectionToken>(
'getRemoteIngressConnectionToken',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'remote-ingress:write',
requireAdminIdentity: true,
});
const manager = this.opsServerRef.dcRouterRef.remoteIngressManager;
if (!manager) {
return { success: false, message: 'RemoteIngress not configured' };
@@ -1,6 +1,7 @@
import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
import { requireOpsAuth } from '../helpers/auth.js';
export class RouteManagementHandler {
public typedrouter = new plugins.typedrequest.TypedRouter();
@@ -18,31 +19,11 @@ export class RouteManagementHandler {
request: { identity?: interfaces.data.IIdentity; apiToken?: string },
requiredScope?: interfaces.data.TApiTokenScope,
): Promise<string> {
// Try JWT identity first
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 */ }
}
// Try API token
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');
const auth = await requireOpsAuth(this.opsServerRef, request, {
scope: requiredScope,
requireAdminIdentity: requiredScope?.endsWith(':write'),
});
return auth.userId;
}
private registerHandlers(): void {
+31 -6
View File
@@ -2,6 +2,7 @@ import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
import { MetricsManager } from '../../monitoring/index.js';
import { requireOpsAuth } from '../helpers/auth.js';
export class SecurityHandler {
constructor(private opsServerRef: OpsServer) {
@@ -17,6 +18,7 @@ export class SecurityHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetSecurityMetrics>(
'getSecurityMetrics',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'security:read' });
const metrics = await this.collectSecurityMetrics();
return {
metrics: {
@@ -43,6 +45,7 @@ export class SecurityHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetActiveConnections>(
'getActiveConnections',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'stats:read' });
const connections = await this.getActiveConnections(dataArg.protocol, dataArg.state);
const connectionInfos: interfaces.data.IConnectionInfo[] = connections.map(conn => ({
id: conn.id,
@@ -82,6 +85,7 @@ export class SecurityHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetNetworkStats>(
'getNetworkStats',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'stats:read' });
// Get network stats from MetricsManager if available
if (this.opsServerRef.dcRouterRef.metricsManager) {
const networkStats = await this.opsServerRef.dcRouterRef.metricsManager.getNetworkStats();
@@ -136,6 +140,7 @@ export class SecurityHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetRateLimitStatus>(
'getRateLimitStatus',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'security:read' });
const status = await this.getRateLimitStatus(dataArg.domain, dataArg.ip);
const limits: interfaces.data.IRateLimitInfo[] = status.limits.map(limit => ({
domain: limit.identifier,
@@ -161,7 +166,8 @@ export class SecurityHandler {
router.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_ListSecurityBlockRules>(
'listSecurityBlockRules',
async () => {
async (dataArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'security:read' });
const manager = this.opsServerRef.dcRouterRef.securityPolicyManager;
return { rules: manager ? await manager.listBlockRules() : [] };
},
@@ -171,7 +177,8 @@ export class SecurityHandler {
router.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_ListIpIntelligence>(
'listIpIntelligence',
async () => {
async (dataArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'security:read' });
const manager = this.opsServerRef.dcRouterRef.securityPolicyManager;
return { records: manager ? await manager.listIpIntelligence() : [] };
},
@@ -181,7 +188,8 @@ export class SecurityHandler {
router.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetCompiledSecurityPolicy>(
'getCompiledSecurityPolicy',
async () => {
async (dataArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'security:read' });
const manager = this.opsServerRef.dcRouterRef.securityPolicyManager;
return {
policy: manager
@@ -196,6 +204,7 @@ export class SecurityHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_ListSecurityPolicyAudit>(
'listSecurityPolicyAudit',
async (dataArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'security:read' });
const manager = this.opsServerRef.dcRouterRef.securityPolicyManager;
return { events: manager ? await manager.listAuditEvents(dataArg.limit || 100) : [] };
},
@@ -208,6 +217,10 @@ export class SecurityHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_CreateSecurityBlockRule>(
'createSecurityBlockRule',
async (dataArg) => {
const auth = await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'security:write',
requireAdminIdentity: true,
});
const manager = this.opsServerRef.dcRouterRef.securityPolicyManager;
if (!manager) return { success: false, message: 'Security policy manager not initialized' };
const rule = await manager.createBlockRule({
@@ -216,7 +229,7 @@ export class SecurityHandler {
matchMode: dataArg.matchMode,
reason: dataArg.reason,
enabled: dataArg.enabled,
}, dataArg.identity.userId);
}, auth.userId);
return { success: true, rule };
},
),
@@ -226,6 +239,10 @@ export class SecurityHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_UpdateSecurityBlockRule>(
'updateSecurityBlockRule',
async (dataArg) => {
const auth = await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'security:write',
requireAdminIdentity: true,
});
const manager = this.opsServerRef.dcRouterRef.securityPolicyManager;
if (!manager) return { success: false, message: 'Security policy manager not initialized' };
const rule = await manager.updateBlockRule(dataArg.id, {
@@ -233,7 +250,7 @@ export class SecurityHandler {
matchMode: dataArg.matchMode,
reason: dataArg.reason,
enabled: dataArg.enabled,
}, dataArg.identity.userId);
}, auth.userId);
return rule ? { success: true, rule } : { success: false, message: 'Rule not found' };
},
),
@@ -243,9 +260,13 @@ export class SecurityHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DeleteSecurityBlockRule>(
'deleteSecurityBlockRule',
async (dataArg) => {
const auth = await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'security:write',
requireAdminIdentity: true,
});
const manager = this.opsServerRef.dcRouterRef.securityPolicyManager;
if (!manager) return { success: false, message: 'Security policy manager not initialized' };
const success = await manager.deleteBlockRule(dataArg.id, dataArg.identity.userId);
const success = await manager.deleteBlockRule(dataArg.id, auth.userId);
return { success, message: success ? undefined : 'Rule not found' };
},
),
@@ -255,6 +276,10 @@ export class SecurityHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_RefreshIpIntelligence>(
'refreshIpIntelligence',
async (dataArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'security:write',
requireAdminIdentity: true,
});
const manager = this.opsServerRef.dcRouterRef.securityPolicyManager;
if (!manager) return { success: false, message: 'Security policy manager not initialized' };
const record = await manager.refreshIpIntelligence(dataArg.ipAddress);
@@ -1,6 +1,7 @@
import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
import { requireOpsAuth } from '../helpers/auth.js';
export class SourceProfileHandler {
public typedrouter = new plugins.typedrequest.TypedRouter();
@@ -14,29 +15,11 @@ export class SourceProfileHandler {
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');
const auth = await requireOpsAuth(this.opsServerRef, request, {
scope: requiredScope,
requireAdminIdentity: requiredScope?.endsWith(':write'),
});
return auth.userId;
}
private registerHandlers(): void {
+7
View File
@@ -4,6 +4,7 @@ import * as interfaces from '../../../ts_interfaces/index.js';
import { MetricsManager } from '../../monitoring/index.js';
import { SecurityLogger } from '../../security/classes.securitylogger.js';
import { commitinfo } from '../../00_commitinfo_data.js';
import { requireOpsAuth } from '../helpers/auth.js';
export class StatsHandler {
constructor(private opsServerRef: OpsServer) {
@@ -19,6 +20,7 @@ export class StatsHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetServerStatistics>(
'getServerStatistics',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'stats:read' });
const stats = await this.collectServerStats();
return {
stats: {
@@ -42,6 +44,7 @@ export class StatsHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetEmailStatistics>(
'getEmailStatistics',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'stats:read' });
const emailServer = this.opsServerRef.dcRouterRef.emailServer;
if (!emailServer) {
return {
@@ -81,6 +84,7 @@ export class StatsHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetDnsStatistics>(
'getDnsStatistics',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'stats:read' });
const dnsServer = this.opsServerRef.dcRouterRef.dnsServer;
if (!dnsServer) {
return {
@@ -118,6 +122,7 @@ export class StatsHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetQueueStatus>(
'getQueueStatus',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'stats:read' });
const emailServer = this.opsServerRef.dcRouterRef.emailServer;
const queues: interfaces.data.IQueueStatus[] = [];
@@ -146,6 +151,7 @@ export class StatsHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetHealthStatus>(
'getHealthStatus',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'stats:read' });
const health = await this.checkHealthStatus();
return {
health: {
@@ -171,6 +177,7 @@ export class StatsHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetCombinedMetrics>(
'getCombinedMetrics',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'stats:read' });
const sections = dataArg.sections || {
server: true,
email: true,
@@ -1,6 +1,7 @@
import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
import { requireOpsAuth } from '../helpers/auth.js';
export class TargetProfileHandler {
public typedrouter = new plugins.typedrequest.TypedRouter();
@@ -14,29 +15,11 @@ export class TargetProfileHandler {
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');
const auth = await requireOpsAuth(this.opsServerRef, request, {
scope: requiredScope,
requireAdminIdentity: requiredScope?.endsWith(':write'),
});
return auth.userId;
}
private registerHandlers(): void {
+46 -3
View File
@@ -1,9 +1,10 @@
import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
import { requireOpsAuth } from '../helpers/auth.js';
/**
* Read-only handler for OpsServer user accounts. Registers on adminRouter,
* Handler for OpsServer user accounts. Registers on adminRouter,
* so admin middleware enforces auth + role check before the handler runs.
* User data is owned by AdminHandler; this handler just exposes a safe
* projection of it via TypedRequest.
@@ -16,15 +17,57 @@ export class UsersHandler {
private registerHandlers(): void {
const router = this.opsServerRef.adminRouter;
// List users (admin-only, read-only)
// List users (admin-only)
router.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_ListUsers>(
'listUsers',
async (_dataArg) => {
async (dataArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'users:read',
requireAdminIdentity: true,
requireAdminToken: true,
});
const users = await this.opsServerRef.adminHandler.listUsers();
return { users };
},
),
);
router.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_CreateUser>(
'createUser',
async (dataArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'users:manage',
requireAdminIdentity: true,
requireAdminToken: true,
});
return this.opsServerRef.adminHandler.createUser({
email: dataArg.email,
name: dataArg.name,
role: dataArg.role,
password: dataArg.password,
enableIdpGlobalAuth: dataArg.enableIdpGlobalAuth,
});
},
),
);
router.addTypedHandler(
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DeleteUser>(
'deleteUser',
async (dataArg) => {
const auth = await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'users:manage',
requireAdminIdentity: true,
requireAdminToken: true,
});
return this.opsServerRef.adminHandler.deleteUser({
id: dataArg.id,
requestingUserId: auth.userId,
});
},
),
);
}
}
+33
View File
@@ -1,6 +1,7 @@
import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
import { requireOpsAuth } from '../helpers/auth.js';
export class VpnHandler {
constructor(private opsServerRef: OpsServer) {
@@ -18,6 +19,7 @@ export class VpnHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetVpnClients>(
'getVpnClients',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'vpn:read' });
const manager = this.opsServerRef.dcRouterRef.vpnManager;
if (!manager) {
return { clients: [] };
@@ -49,6 +51,7 @@ export class VpnHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetVpnStatus>(
'getVpnStatus',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'vpn:read' });
const manager = this.opsServerRef.dcRouterRef.vpnManager;
const vpnConfig = this.opsServerRef.dcRouterRef.options.vpnConfig;
if (!manager) {
@@ -84,6 +87,7 @@ export class VpnHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetVpnConnectedClients>(
'getVpnConnectedClients',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'vpn:read' });
const manager = this.opsServerRef.dcRouterRef.vpnManager;
if (!manager) {
return { connectedClients: [] };
@@ -111,6 +115,10 @@ export class VpnHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_CreateVpnClient>(
'createVpnClient',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'vpn:write',
requireAdminIdentity: true,
});
const manager = this.opsServerRef.dcRouterRef.vpnManager;
if (!manager) {
return { success: false, message: 'VPN not configured' };
@@ -168,6 +176,10 @@ export class VpnHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_UpdateVpnClient>(
'updateVpnClient',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'vpn:write',
requireAdminIdentity: true,
});
const manager = this.opsServerRef.dcRouterRef.vpnManager;
if (!manager) {
return { success: false, message: 'VPN not configured' };
@@ -198,6 +210,10 @@ export class VpnHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DeleteVpnClient>(
'deleteVpnClient',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'vpn:write',
requireAdminIdentity: true,
});
const manager = this.opsServerRef.dcRouterRef.vpnManager;
if (!manager) {
return { success: false, message: 'VPN not configured' };
@@ -218,6 +234,10 @@ export class VpnHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_EnableVpnClient>(
'enableVpnClient',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'vpn:write',
requireAdminIdentity: true,
});
const manager = this.opsServerRef.dcRouterRef.vpnManager;
if (!manager) {
return { success: false, message: 'VPN not configured' };
@@ -238,6 +258,10 @@ export class VpnHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DisableVpnClient>(
'disableVpnClient',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'vpn:write',
requireAdminIdentity: true,
});
const manager = this.opsServerRef.dcRouterRef.vpnManager;
if (!manager) {
return { success: false, message: 'VPN not configured' };
@@ -258,6 +282,10 @@ export class VpnHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_RotateVpnClientKey>(
'rotateVpnClientKey',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'vpn:write',
requireAdminIdentity: true,
});
const manager = this.opsServerRef.dcRouterRef.vpnManager;
if (!manager) {
return { success: false, message: 'VPN not configured' };
@@ -281,6 +309,10 @@ export class VpnHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_ExportVpnClientConfig>(
'exportVpnClientConfig',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, {
scope: 'vpn:write',
requireAdminIdentity: true,
});
const manager = this.opsServerRef.dcRouterRef.vpnManager;
if (!manager) {
return { success: false, message: 'VPN not configured' };
@@ -301,6 +333,7 @@ export class VpnHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetVpnClientTelemetry>(
'getVpnClientTelemetry',
async (dataArg, toolsArg) => {
await requireOpsAuth(this.opsServerRef, dataArg, { scope: 'vpn:read' });
const manager = this.opsServerRef.dcRouterRef.vpnManager;
if (!manager) {
return { success: false, message: 'VPN not configured' };
+18 -33
View File
@@ -1,6 +1,7 @@
import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
import { requireOpsAuth } from '../helpers/auth.js';
type TAuthContext = {
userId: string;
@@ -20,39 +21,23 @@ export class WorkHosterHandler {
request: { identity?: interfaces.data.IIdentity; apiToken?: string },
requiredScope?: interfaces.data.TApiTokenScope,
): Promise<TAuthContext> {
if (request.identity?.jwt) {
try {
const isAdmin = await this.opsServerRef.adminHandler.adminIdentityGuard.exec({
identity: request.identity,
});
if (isAdmin) return { userId: request.identity.userId, isAdmin: true };
} 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 { userId: token.createdBy, isAdmin: token.policy?.role === 'admin', token };
}
throw new plugins.typedrequest.TypedResponseError('insufficient scope');
}
}
}
throw new plugins.typedrequest.TypedResponseError('unauthorized');
const auth = await requireOpsAuth(this.opsServerRef, request, {
scope: requiredScope,
requireAdminIdentity: requiredScope?.endsWith(':write'),
});
return { userId: auth.userId, isAdmin: auth.isAdmin, token: auth.token };
}
private async requireAdmin(request: { identity?: interfaces.data.IIdentity }): Promise<string> {
if (request.identity?.jwt) {
const isAdmin = await this.opsServerRef.adminHandler.adminIdentityGuard.exec({
identity: request.identity,
});
if (isAdmin) return request.identity.userId;
}
throw new plugins.typedrequest.TypedResponseError('admin identity required');
private async requireAdmin(
request: { identity?: interfaces.data.IIdentity; apiToken?: string },
scope: interfaces.data.TApiTokenScope = 'gateway-clients:write',
): Promise<string> {
const auth = await requireOpsAuth(this.opsServerRef, request, {
scope,
requireAdminIdentity: true,
requireAdminToken: true,
});
return auth.userId;
}
private registerHandlers(): void {
@@ -83,7 +68,7 @@ export class WorkHosterHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_ListGatewayClients>(
'listGatewayClients',
async (dataArg) => {
await this.requireAdmin(dataArg);
await this.requireAdmin(dataArg, 'gateway-clients:read');
return { gatewayClients: await this.listManagedGatewayClients() };
},
),
@@ -154,7 +139,7 @@ export class WorkHosterHandler {
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_CreateGatewayClientToken>(
'createGatewayClientToken',
async (dataArg) => {
const userId = await this.requireAdmin(dataArg);
const userId = await this.requireAdmin(dataArg, 'tokens:manage');
const gatewayClient = await this.opsServerRef.dcRouterRef.gatewayClientManager?.getClient(dataArg.gatewayClientId);
const tokenManager = this.opsServerRef.dcRouterRef.apiTokenManager;
if (!gatewayClient || !gatewayClient.enabled) {
+91
View File
@@ -0,0 +1,91 @@
import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
export interface IAuthRequest {
identity?: interfaces.data.IIdentity;
apiToken?: string;
}
export interface IAuthRequirement {
scope?: interfaces.data.TApiTokenScope;
requireAdminIdentity?: boolean;
requireAdminToken?: boolean;
}
export interface IAuthContext {
type: 'identity' | 'apiToken';
userId: string;
role?: string;
isAdmin: boolean;
scopes: interfaces.data.TApiTokenScope[];
identity?: interfaces.data.IIdentity;
token?: interfaces.data.IStoredApiToken;
}
const typedAuthError = (messageArg: string) => {
return new plugins.typedrequest.TypedResponseError(messageArg);
};
export async function requireOpsAuth(
opsServerRefArg: OpsServer,
requestArg: IAuthRequest,
requirementArg: IAuthRequirement = {},
): Promise<IAuthContext> {
let identityNeedsAdmin = false;
let tokenNeedsAdmin = false;
let tokenNeedsScope = false;
if (requestArg.identity?.jwt) {
const identity = await opsServerRefArg.adminHandler.validateIdentity(requestArg.identity);
if (identity) {
const isAdmin = identity.role === 'admin';
if (!requirementArg.requireAdminIdentity || isAdmin) {
return {
type: 'identity',
userId: identity.userId,
role: identity.role,
isAdmin,
scopes: [],
identity,
};
}
identityNeedsAdmin = true;
}
}
if (requestArg.apiToken) {
const tokenManager = opsServerRefArg.dcRouterRef.apiTokenManager;
const token = tokenManager ? await tokenManager.validateToken(requestArg.apiToken) : null;
if (token) {
if (requirementArg.requireAdminToken && token.policy?.role !== 'admin') {
tokenNeedsAdmin = true;
} else if (requirementArg.scope && !tokenManager!.hasScope(token, requirementArg.scope)) {
tokenNeedsScope = true;
} else {
const scopes = token.policy?.role === 'admin'
? ['*' as interfaces.data.TApiTokenScope]
: Array.from(new Set([...(token.scopes || []), ...(token.policy?.scopes || [])]));
return {
type: 'apiToken',
userId: token.createdBy,
role: token.policy?.role || 'operator',
isAdmin: token.policy?.role === 'admin',
scopes,
token,
};
}
}
}
if (tokenNeedsScope) {
throw typedAuthError('insufficient scope');
}
if (tokenNeedsAdmin) {
throw typedAuthError('admin API token required');
}
if (identityNeedsAdmin) {
throw typedAuthError('admin identity required');
}
throw typedAuthError('unauthorized');
}
+46 -16
View File
@@ -8,22 +8,52 @@ export type IRouteSecurity = NonNullable<IRouteConfig['security']>;
// Route Management Data Types
// ============================================================================
export type TApiTokenScope =
| '*'
| 'routes:read' | 'routes:write'
| 'config:read'
| 'certificates:read' | 'certificates:write'
| 'tokens:read' | 'tokens:manage'
| 'source-profiles:read' | 'source-profiles:write'
| 'target-profiles:read' | 'target-profiles:write'
| 'targets:read' | 'targets:write'
| 'dns-providers:read' | 'dns-providers:write'
| 'domains:read' | 'domains:write'
| 'dns-records:read' | 'dns-records:write'
| 'acme-config:read' | 'acme-config:write'
| 'email-domains:read' | 'email-domains:write'
| 'gateway-clients:read' | 'gateway-clients:write'
| 'workhosters:read' | 'workhosters:write';
export const apiTokenScopes = [
'*',
'routes:read',
'routes:write',
'config:read',
'stats:read',
'logs:read',
'security:read',
'security:write',
'emails:read',
'emails:write',
'certificates:read',
'certificates:write',
'tokens:read',
'tokens:manage',
'users:read',
'users:manage',
'source-profiles:read',
'source-profiles:write',
'target-profiles:read',
'target-profiles:write',
'targets:read',
'targets:write',
'dns-providers:read',
'dns-providers:write',
'domains:read',
'domains:write',
'dns-records:read',
'dns-records:write',
'acme-config:read',
'acme-config:write',
'email-domains:read',
'email-domains:write',
'remote-ingress:read',
'remote-ingress:write',
'vpn:read',
'vpn:write',
'radius:read',
'radius:write',
'gateway-clients:read',
'gateway-clients:write',
'workhosters:read',
'workhosters:write',
] as const;
export type TApiTokenScope = typeof apiTokenScopes[number];
export type TGatewayClientType = 'onebox' | 'cloudly' | 'custom';
/** @deprecated Use TGatewayClientType. */
+1 -1
View File
@@ -68,7 +68,7 @@ for (const route of response.routes) {
## Bootstrap Contracts
The auth request group includes `getAdminBootstrapStatus` and `createInitialAdminUser`. These exist so a fresh DB-backed dcrouter can require explicit first-admin creation instead of auto-persisting a default account. `createInitialAdminUser` requires the temporary bootstrap identity and can optionally enable `idp.global` authentication for the same normalized local email.
The auth request group includes `getAdminBootstrapStatus` and `createInitialAdminUser`. These exist so a fresh DB-backed dcrouter can require explicit first-admin creation instead of auto-persisting a default account. `createInitialAdminUser` requires the temporary bootstrap identity and can optionally enable `idp.global` authentication for the same normalized local email. The SDK defaults to hosted `https://idp.global`; dcrouter URL settings are overrides only.
## When To Use It
+10 -5
View File
@@ -16,7 +16,8 @@ export interface IReq_CreateApiToken extends plugins.typedrequestInterfaces.impl
> {
method: 'createApiToken';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
name: string;
scopes: TApiTokenScope[];
policy?: IApiTokenPolicy;
@@ -39,7 +40,8 @@ export interface IReq_ListApiTokens extends plugins.typedrequestInterfaces.imple
> {
method: 'listApiTokens';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
};
response: {
tokens: IApiTokenInfo[];
@@ -55,7 +57,8 @@ export interface IReq_RevokeApiToken extends plugins.typedrequestInterfaces.impl
> {
method: 'revokeApiToken';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
id: string;
};
response: {
@@ -74,7 +77,8 @@ export interface IReq_RollApiToken extends plugins.typedrequestInterfaces.implem
> {
method: 'rollApiToken';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
id: string;
};
response: {
@@ -93,7 +97,8 @@ export interface IReq_ToggleApiToken extends plugins.typedrequestInterfaces.impl
> {
method: 'toggleApiToken';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
id: string;
enabled: boolean;
};
+3 -2
View File
@@ -3,7 +3,8 @@ import type * as data from '../data/index.js';
export interface IReq_GetCombinedMetrics {
method: 'getCombinedMetrics';
request: {
identity: data.IIdentity;
identity?: data.IIdentity;
apiToken?: string;
sections?: {
server?: boolean;
email?: boolean;
@@ -26,4 +27,4 @@ export interface IReq_GetCombinedMetrics {
};
timestamp: number;
};
}
}
+2 -1
View File
@@ -82,7 +82,8 @@ export interface IReq_GetConfiguration extends plugins.typedrequestInterfaces.im
> {
method: 'getConfiguration';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
section?: string;
};
response: {
+6 -3
View File
@@ -68,7 +68,8 @@ export interface IReq_GetAllEmails extends plugins.typedrequestInterfaces.implem
> {
method: 'getAllEmails';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
};
response: {
emails: IEmail[];
@@ -84,7 +85,8 @@ export interface IReq_GetEmailDetail extends plugins.typedrequestInterfaces.impl
> {
method: 'getEmailDetail';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
emailId: string;
};
response: {
@@ -101,7 +103,8 @@ export interface IReq_ResendEmail extends plugins.typedrequestInterfaces.impleme
> {
method: 'resendEmail';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
emailId: string;
};
response: {
+5 -3
View File
@@ -9,7 +9,8 @@ export interface IReq_GetRecentLogs extends plugins.typedrequestInterfaces.imple
> {
method: 'getRecentLogs';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
level?: 'debug' | 'info' | 'warn' | 'error';
category?: 'smtp' | 'dns' | 'security' | 'system' | 'email';
limit?: number;
@@ -31,7 +32,8 @@ export interface IReq_GetLogStream extends plugins.typedrequestInterfaces.implem
> {
method: 'getLogStream';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
follow?: boolean;
filters?: {
level?: string[];
@@ -53,4 +55,4 @@ export interface IReq_PushLogEntry extends plugins.typedrequestInterfaces.implem
entry: statsInterfaces.ILogEntry;
};
response: {};
}
}
+24 -12
View File
@@ -14,7 +14,8 @@ export interface IReq_GetRadiusClients extends plugins.typedrequestInterfaces.im
> {
method: 'getRadiusClients';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
};
response: {
clients: Array<{
@@ -35,7 +36,8 @@ export interface IReq_SetRadiusClient extends plugins.typedrequestInterfaces.imp
> {
method: 'setRadiusClient';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
client: {
name: string;
ipRange: string;
@@ -59,7 +61,8 @@ export interface IReq_RemoveRadiusClient extends plugins.typedrequestInterfaces.
> {
method: 'removeRadiusClient';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
name: string;
};
response: {
@@ -81,7 +84,8 @@ export interface IReq_GetVlanMappings extends plugins.typedrequestInterfaces.imp
> {
method: 'getVlanMappings';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
};
response: {
mappings: Array<{
@@ -108,7 +112,8 @@ export interface IReq_SetVlanMapping extends plugins.typedrequestInterfaces.impl
> {
method: 'setVlanMapping';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
mapping: {
mac: string;
vlan: number;
@@ -139,7 +144,8 @@ export interface IReq_RemoveVlanMapping extends plugins.typedrequestInterfaces.i
> {
method: 'removeVlanMapping';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
mac: string;
};
response: {
@@ -157,7 +163,8 @@ export interface IReq_UpdateVlanConfig extends plugins.typedrequestInterfaces.im
> {
method: 'updateVlanConfig';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
defaultVlan?: number;
allowUnknownMacs?: boolean;
};
@@ -179,7 +186,8 @@ export interface IReq_TestVlanAssignment extends plugins.typedrequestInterfaces.
> {
method: 'testVlanAssignment';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
mac: string;
};
response: {
@@ -207,7 +215,8 @@ export interface IReq_GetRadiusSessions extends plugins.typedrequestInterfaces.i
> {
method: 'getRadiusSessions';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
filter?: {
username?: string;
nasIpAddress?: string;
@@ -243,7 +252,8 @@ export interface IReq_DisconnectRadiusSession extends plugins.typedrequestInterf
> {
method: 'disconnectRadiusSession';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
sessionId: string;
reason?: string;
};
@@ -262,7 +272,8 @@ export interface IReq_GetRadiusAccountingSummary extends plugins.typedrequestInt
> {
method: 'getRadiusAccountingSummary';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
startTime: number;
endTime: number;
};
@@ -296,7 +307,8 @@ export interface IReq_GetRadiusStatistics extends plugins.typedrequestInterfaces
> {
method: 'getRadiusStatistics';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
};
response: {
stats: {
+14 -7
View File
@@ -15,7 +15,8 @@ export interface IReq_CreateRemoteIngress extends plugins.typedrequestInterfaces
> {
method: 'createRemoteIngress';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
name: string;
listenPorts?: number[];
autoDerivePorts?: boolean;
@@ -36,7 +37,8 @@ export interface IReq_DeleteRemoteIngress extends plugins.typedrequestInterfaces
> {
method: 'deleteRemoteIngress';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
id: string;
};
response: {
@@ -54,7 +56,8 @@ export interface IReq_UpdateRemoteIngress extends plugins.typedrequestInterfaces
> {
method: 'updateRemoteIngress';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
id: string;
name?: string;
listenPorts?: number[];
@@ -77,7 +80,8 @@ export interface IReq_RegenerateRemoteIngressSecret extends plugins.typedrequest
> {
method: 'regenerateRemoteIngressSecret';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
id: string;
};
response: {
@@ -95,7 +99,8 @@ export interface IReq_GetRemoteIngresses extends plugins.typedrequestInterfaces.
> {
method: 'getRemoteIngresses';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
};
response: {
edges: IRemoteIngress[];
@@ -111,7 +116,8 @@ export interface IReq_GetRemoteIngressStatus extends plugins.typedrequestInterfa
> {
method: 'getRemoteIngressStatus';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
};
response: {
statuses: IRemoteIngressStatus[];
@@ -128,7 +134,8 @@ export interface IReq_GetRemoteIngressConnectionToken extends plugins.typedreque
> {
method: 'getRemoteIngressConnectionToken';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
edgeId: string;
hubHost?: string;
};
+16 -8
View File
@@ -15,7 +15,8 @@ export interface IReq_ListSecurityBlockRules extends plugins.typedrequestInterfa
> {
method: 'listSecurityBlockRules';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
};
response: {
rules: ISecurityBlockRule[];
@@ -28,7 +29,8 @@ export interface IReq_CreateSecurityBlockRule extends plugins.typedrequestInterf
> {
method: 'createSecurityBlockRule';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
type: TSecurityBlockRuleType;
value: string;
matchMode?: TSecurityBlockRuleMatchMode;
@@ -48,7 +50,8 @@ export interface IReq_UpdateSecurityBlockRule extends plugins.typedrequestInterf
> {
method: 'updateSecurityBlockRule';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
id: string;
value?: string;
matchMode?: TSecurityBlockRuleMatchMode;
@@ -68,7 +71,8 @@ export interface IReq_DeleteSecurityBlockRule extends plugins.typedrequestInterf
> {
method: 'deleteSecurityBlockRule';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
id: string;
};
response: {
@@ -83,7 +87,8 @@ export interface IReq_ListIpIntelligence extends plugins.typedrequestInterfaces.
> {
method: 'listIpIntelligence';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
};
response: {
records: IIpIntelligenceRecord[];
@@ -96,7 +101,8 @@ export interface IReq_GetCompiledSecurityPolicy extends plugins.typedrequestInte
> {
method: 'getCompiledSecurityPolicy';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
};
response: {
policy: ISecurityCompiledPolicy;
@@ -109,7 +115,8 @@ export interface IReq_ListSecurityPolicyAudit extends plugins.typedrequestInterf
> {
method: 'listSecurityPolicyAudit';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
limit?: number;
};
response: {
@@ -123,7 +130,8 @@ export interface IReq_RefreshIpIntelligence extends plugins.typedrequestInterfac
> {
method: 'refreshIpIntelligence';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
ipAddress: string;
};
response: {
+19 -10
View File
@@ -9,7 +9,8 @@ export interface IReq_GetServerStatistics extends plugins.typedrequestInterfaces
> {
method: 'getServerStatistics';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
includeHistory?: boolean;
timeRange?: '1h' | '6h' | '24h' | '7d' | '30d';
};
@@ -29,7 +30,8 @@ export interface IReq_GetEmailStatistics extends plugins.typedrequestInterfaces.
> {
method: 'getEmailStatistics';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
timeRange?: '1h' | '6h' | '24h' | '7d' | '30d';
domain?: string;
includeDetails?: boolean;
@@ -49,7 +51,8 @@ export interface IReq_GetDnsStatistics extends plugins.typedrequestInterfaces.im
> {
method: 'getDnsStatistics';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
timeRange?: '1h' | '6h' | '24h' | '7d' | '30d';
domain?: string;
includeQueryTypes?: boolean;
@@ -69,7 +72,8 @@ export interface IReq_GetRateLimitStatus extends plugins.typedrequestInterfaces.
> {
method: 'getRateLimitStatus';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
domain?: string;
ip?: string;
includeBlocked?: boolean;
@@ -91,7 +95,8 @@ export interface IReq_GetSecurityMetrics extends plugins.typedrequestInterfaces.
> {
method: 'getSecurityMetrics';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
timeRange?: '1h' | '6h' | '24h' | '7d' | '30d';
includeDetails?: boolean;
};
@@ -112,7 +117,8 @@ export interface IReq_GetActiveConnections extends plugins.typedrequestInterface
> {
method: 'getActiveConnections';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
protocol?: 'smtp' | 'smtps' | 'http' | 'https';
state?: string;
};
@@ -137,7 +143,8 @@ export interface IReq_GetQueueStatus extends plugins.typedrequestInterfaces.impl
> {
method: 'getQueueStatus';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
queueName?: string;
};
response: {
@@ -153,7 +160,8 @@ export interface IReq_GetHealthStatus extends plugins.typedrequestInterfaces.imp
> {
method: 'getHealthStatus';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
detailed?: boolean;
};
response: {
@@ -168,7 +176,8 @@ export interface IReq_GetNetworkStats extends plugins.typedrequestInterfaces.imp
> {
method: 'getNetworkStats';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
};
response: {
connectionsByIP: Array<{ ip: string; count: number }>;
@@ -185,4 +194,4 @@ export interface IReq_GetNetworkStats extends plugins.typedrequestInterfaces.imp
frontendProtocols?: statsInterfaces.IProtocolDistribution | null;
backendProtocols?: statsInterfaces.IProtocolDistribution | null;
};
}
}
+48 -2
View File
@@ -2,8 +2,10 @@ import * as plugins from '../plugins.js';
import * as authInterfaces from '../data/auth.js';
import type { IAdminUserProjection } from './admin.js';
export type TUserManagementRole = 'admin' | 'user';
/**
* List all OpsServer users (admin-only, read-only).
* List all OpsServer users (admin-only).
* Deliberately omits password/secret fields from the response.
*/
export interface IReq_ListUsers extends plugins.typedrequestInterfaces.implementsTR<
@@ -12,9 +14,53 @@ export interface IReq_ListUsers extends plugins.typedrequestInterfaces.implement
> {
method: 'listUsers';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
};
response: {
users: IAdminUserProjection[];
};
}
/**
* Create a persisted OpsServer user account (admin-only).
*/
export interface IReq_CreateUser extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_CreateUser
> {
method: 'createUser';
request: {
identity?: authInterfaces.IIdentity;
apiToken?: string;
email: string;
name?: string;
role: TUserManagementRole;
password: string;
enableIdpGlobalAuth?: boolean;
};
response: {
success: boolean;
user?: IAdminUserProjection;
message?: string;
};
}
/**
* Delete a persisted OpsServer user account (admin-only).
*/
export interface IReq_DeleteUser extends plugins.typedrequestInterfaces.implementsTR<
plugins.typedrequestInterfaces.ITypedRequest,
IReq_DeleteUser
> {
method: 'deleteUser';
request: {
identity?: authInterfaces.IIdentity;
apiToken?: string;
id: string;
};
response: {
success: boolean;
message?: string;
};
}
+22 -11
View File
@@ -15,7 +15,8 @@ export interface IReq_GetVpnClients extends plugins.typedrequestInterfaces.imple
> {
method: 'getVpnClients';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
};
response: {
clients: IVpnClient[];
@@ -31,7 +32,8 @@ export interface IReq_GetVpnStatus extends plugins.typedrequestInterfaces.implem
> {
method: 'getVpnStatus';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
};
response: {
status: IVpnServerStatus;
@@ -47,7 +49,8 @@ export interface IReq_CreateVpnClient extends plugins.typedrequestInterfaces.imp
> {
method: 'createVpnClient';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
clientId: string;
targetProfileIds?: string[];
description?: string;
@@ -78,7 +81,8 @@ export interface IReq_UpdateVpnClient extends plugins.typedrequestInterfaces.imp
> {
method: 'updateVpnClient';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
clientId: string;
description?: string;
targetProfileIds?: string[];
@@ -106,7 +110,8 @@ export interface IReq_GetVpnConnectedClients extends plugins.typedrequestInterfa
> {
method: 'getVpnConnectedClients';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
};
response: {
connectedClients: IVpnConnectedClient[];
@@ -122,7 +127,8 @@ export interface IReq_DeleteVpnClient extends plugins.typedrequestInterfaces.imp
> {
method: 'deleteVpnClient';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
clientId: string;
};
response: {
@@ -140,7 +146,8 @@ export interface IReq_EnableVpnClient extends plugins.typedrequestInterfaces.imp
> {
method: 'enableVpnClient';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
clientId: string;
};
response: {
@@ -158,7 +165,8 @@ export interface IReq_DisableVpnClient extends plugins.typedrequestInterfaces.im
> {
method: 'disableVpnClient';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
clientId: string;
};
response: {
@@ -176,7 +184,8 @@ export interface IReq_RotateVpnClientKey extends plugins.typedrequestInterfaces.
> {
method: 'rotateVpnClientKey';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
clientId: string;
};
response: {
@@ -196,7 +205,8 @@ export interface IReq_ExportVpnClientConfig extends plugins.typedrequestInterfac
> {
method: 'exportVpnClientConfig';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
clientId: string;
format: 'smartvpn' | 'wireguard';
};
@@ -216,7 +226,8 @@ export interface IReq_GetVpnClientTelemetry extends plugins.typedrequestInterfac
> {
method: 'getVpnClientTelemetry';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
clientId: string;
};
response: {
+10 -5
View File
@@ -53,7 +53,8 @@ export interface IReq_ListGatewayClients extends plugins.typedrequestInterfaces.
> {
method: 'listGatewayClients';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
};
response: {
gatewayClients: IGatewayClient[];
@@ -66,7 +67,8 @@ export interface IReq_CreateGatewayClient extends plugins.typedrequestInterfaces
> {
method: 'createGatewayClient';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
id?: string;
type: IGatewayClient['type'];
name: string;
@@ -88,7 +90,8 @@ export interface IReq_UpdateGatewayClient extends plugins.typedrequestInterfaces
> {
method: 'updateGatewayClient';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
id: string;
name?: string;
description?: string;
@@ -110,7 +113,8 @@ export interface IReq_DeleteGatewayClient extends plugins.typedrequestInterfaces
> {
method: 'deleteGatewayClient';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
id: string;
};
response: {
@@ -125,7 +129,8 @@ export interface IReq_CreateGatewayClientToken extends plugins.typedrequestInter
> {
method: 'createGatewayClientToken';
request: {
identity: authInterfaces.IIdentity;
identity?: authInterfaces.IIdentity;
apiToken?: string;
gatewayClientId: string;
name?: string;
expiresInDays?: number | null;
+2
View File
@@ -89,6 +89,8 @@ export async function createMigrationRunner(
db: db as any,
// Brand-new installs skip all migrations and stamp directly to the current version.
freshInstallVersion: targetVersion,
// dcrouter uses the package version as targetVersion; bridge releases without DB changes.
targetVersionStrategy: 'bridge',
});
// Register steps in execution order. Each step's .from() must match the
+1 -1
View File
@@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@serve.zone/dcrouter',
version: '13.30.0',
version: '13.32.0',
description: 'A multifaceted routing service handling mail and SMS delivery functions.'
}
+69 -1
View File
@@ -2637,7 +2637,7 @@ export async function createGatewayClientToken(
});
}
// Users (read-only list)
// Users
export const fetchUsersAction = usersStatePart.createAction(async (statePartArg): Promise<IUsersState> => {
const context = getActionContext();
const currentState = statePartArg.getState()!;
@@ -2666,6 +2666,74 @@ export const fetchUsersAction = usersStatePart.createAction(async (statePartArg)
}
});
export const createUserAction = usersStatePart.createAction<{
email: string;
name?: string;
role: interfaces.requests.TUserManagementRole;
password: string;
enableIdpGlobalAuth?: boolean;
}>(async (statePartArg, dataArg, actionContext): Promise<IUsersState> => {
const context = getActionContext();
const currentState = statePartArg.getState()!;
if (!context.identity) return currentState;
try {
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_CreateUser
>('/typedrequest', 'createUser');
const response = await request.fire({
identity: context.identity,
email: dataArg.email,
name: dataArg.name,
role: dataArg.role,
password: dataArg.password,
enableIdpGlobalAuth: dataArg.enableIdpGlobalAuth,
});
if (!response.success) {
throw new Error(response.message || 'Failed to create user');
}
return await actionContext!.dispatch(fetchUsersAction, null);
} catch (error) {
return {
...currentState,
error: error instanceof Error ? error.message : 'Failed to create user',
};
}
});
export const deleteUserAction = usersStatePart.createAction<string>(
async (statePartArg, userIdArg, actionContext): Promise<IUsersState> => {
const context = getActionContext();
const currentState = statePartArg.getState()!;
if (!context.identity) return currentState;
try {
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
interfaces.requests.IReq_DeleteUser
>('/typedrequest', 'deleteUser');
const response = await request.fire({
identity: context.identity,
id: userIdArg,
});
if (!response.success) {
throw new Error(response.message || 'Failed to delete user');
}
return await actionContext!.dispatch(fetchUsersAction, null);
} catch (error) {
return {
...currentState,
error: error instanceof Error ? error.message : 'Failed to delete user',
};
}
},
);
export async function createApiToken(
name: string,
scopes: interfaces.data.TApiTokenScope[],
+1 -20
View File
@@ -200,26 +200,7 @@ export class OpsViewApiTokens extends DeesElement {
private async showCreateTokenDialog() {
const { DeesModal } = await import('@design.estate/dees-catalog');
const allScopes = [
'*',
'routes:read',
'routes:write',
'config:read',
'certificates:read',
'certificates:write',
'tokens:read',
'tokens:manage',
'domains:read',
'domains:write',
'dns-records:read',
'dns-records:write',
'email-domains:read',
'email-domains:write',
'gateway-clients:read',
'gateway-clients:write',
'workhosters:read',
'workhosters:write',
];
const allScopes = [...interfaces.data.apiTokenScopes];
await DeesModal.createAndShow({
heading: 'Create API Token',
+139 -1
View File
@@ -116,12 +116,31 @@ export class OpsViewUsers extends DeesElement {
.showColumnFilters=${true}
.displayFunction=${(user: appstate.IUser) => ({
ID: html`<span class="userIdCell">${user.id}</span>`,
Username: user.username,
Email: user.email || user.username,
Name: user.name || '',
Role: this.renderRoleBadge(user.role),
Status: user.status || 'active',
Auth: (user.authSources || []).join(', ') || 'bootstrap',
Session: user.id === currentUserId
? html`<span class="sessionBadge">current</span>`
: '',
})}
.dataActions=${[
{
name: 'Create User',
iconName: 'lucide:userPlus',
type: ['header'],
actionFunc: async () => await this.showCreateUserDialog(),
},
{
name: 'Delete',
iconName: 'lucide:trash2',
type: ['inRow', 'contextmenu'] as any,
actionFunc: async (actionData: any) => {
await this.showDeleteUserDialog(actionData.item as appstate.IUser);
},
},
]}
></dees-table>
</div>
`;
@@ -132,6 +151,125 @@ export class OpsViewUsers extends DeesElement {
return html`<span class="roleBadge ${cls}">${role}</span>`;
}
private async showCreateUserDialog(): Promise<void> {
const { DeesModal, DeesToast } = await import('@design.estate/dees-catalog');
await DeesModal.createAndShow({
heading: 'Create User',
content: html`
<dees-form>
<dees-input-text .key=${'email'} .label=${'Email'} .required=${true}></dees-input-text>
<dees-input-text .key=${'name'} .label=${'Display name'}></dees-input-text>
<dees-input-dropdown
.key=${'role'}
.label=${'Role'}
.options=${[
{ option: 'User', key: 'user' },
{ option: 'Admin', key: 'admin' },
]}
.selectedOption=${{ option: 'User', key: 'user' }}
.required=${true}
></dees-input-dropdown>
<dees-input-text .key=${'password'} .label=${'Password'} .required=${true} .isPasswordBool=${true}></dees-input-text>
<dees-input-text .key=${'passwordConfirm'} .label=${'Confirm password'} .required=${true} .isPasswordBool=${true}></dees-input-text>
<dees-input-checkbox
.key=${'enableIdpGlobalAuth'}
.label=${'Allow idp.global login for this email'}
.description=${'Uses https://idp.global by default; the local dcrouter account and role remain authoritative.'}
></dees-input-checkbox>
</dees-form>
`,
menuOptions: [
{
name: 'Cancel',
iconName: 'lucide:x',
action: async (modalArg: any) => await modalArg.destroy(),
},
{
name: 'Create',
iconName: 'lucide:userPlus',
action: async (modalArg: any) => {
const form = modalArg.shadowRoot?.querySelector('.content')?.querySelector('dees-form') as any;
if (!form) return;
const data = await form.collectFormData();
const email = String(data.email || '').trim();
const name = String(data.name || '').trim();
const password = String(data.password || '');
const passwordConfirm = String(data.passwordConfirm || '');
const roleValue = String(data.role?.key ?? data.role ?? 'user');
if (!email || !password) {
form.setStatus?.('error', 'Email and password are required.');
return;
}
if (password !== passwordConfirm) {
form.setStatus?.('error', 'Passwords do not match.');
return;
}
form.setStatus?.('pending', 'Creating user...');
await appstate.usersStatePart.dispatchAction(appstate.createUserAction, {
email,
name,
role: roleValue === 'admin' ? 'admin' : 'user',
password,
enableIdpGlobalAuth: Boolean(data.enableIdpGlobalAuth),
});
const state = appstate.usersStatePart.getState();
if (state?.error) {
form.setStatus?.('error', state.error);
return;
}
DeesToast.show({ message: `User created for ${email}`, type: 'success', duration: 3000 });
await modalArg.destroy();
},
},
],
});
}
private async showDeleteUserDialog(userArg: appstate.IUser): Promise<void> {
const { DeesModal, DeesToast } = await import('@design.estate/dees-catalog');
const currentUserId = this.loginState.identity?.userId;
if (userArg.id === currentUserId) {
DeesToast.show({ message: 'You cannot delete the current user.', type: 'error', duration: 4000 });
return;
}
await DeesModal.createAndShow({
heading: 'Delete User',
content: html`
<div style="padding: 8px 0; font-size: 14px; line-height: 1.5;">
<p>Delete <strong>${userArg.email || userArg.username}</strong>?</p>
<p style="color: #f59e0b; margin-top: 12px;">This removes the local dcrouter account and cannot be undone.</p>
</div>
`,
menuOptions: [
{
name: 'Cancel',
iconName: 'lucide:x',
action: async (modalArg: any) => await modalArg.destroy(),
},
{
name: 'Delete',
iconName: 'lucide:trash2',
action: async (modalArg: any) => {
await appstate.usersStatePart.dispatchAction(appstate.deleteUserAction, userArg.id);
const state = appstate.usersStatePart.getState();
if (state?.error) {
DeesToast.show({ message: state.error, type: 'error', duration: 4000 });
return;
}
DeesToast.show({ message: 'User deleted.', type: 'success', duration: 3000 });
await modalArg.destroy();
},
},
],
});
}
async firstUpdated() {
if (this.loginState.isLoggedIn) {
await appstate.usersStatePart.dispatchAction(appstate.fetchUsersAction, null);
@@ -271,6 +271,7 @@ export class OpsViewRoutes extends DeesElement {
const tags = [...(mr.route.tags || [])];
tags.push(mr.origin);
if (!mr.enabled) tags.push('disabled');
if (mr.route.vpnOnly) tags.push('vpn-only');
return {
...mr.route,
@@ -360,6 +361,7 @@ export class OpsViewRoutes extends DeesElement {
<div style="color: #ccc; padding: 8px 0;">
<p>Origin: <strong style="color: #0af;">${merged.origin}</strong></p>
<p>Status: <strong>${merged.enabled ? 'Enabled' : 'Disabled'}</strong></p>
${merged.route.vpnOnly ? html`<p>Access: <strong style="color: #22c55e;">VPN only</strong></p>` : ''}
<p>ID: <code style="color: #888;">${merged.id}</code></p>
${isSystemManaged ? html`<p>This route is system-managed. Change its source config to modify it directly.</p>` : ''}
${meta?.sourceProfileName ? html`<p>Source Profile: <strong style="color: #a78bfa;">${meta.sourceProfileName}</strong></p>` : ''}
@@ -491,6 +493,7 @@ export class OpsViewRoutes extends DeesElement {
? (Array.isArray(firstTarget.host) ? firstTarget.host[0] : firstTarget.host)
: '';
const currentTargetPort = typeof firstTarget?.port === 'number' ? String(firstTarget.port) : '';
const currentVpnOnly = route.vpnOnly === true;
const currentRemoteIngressEnabled = route.remoteIngress?.enabled === true;
const currentEdgeFilter = route.remoteIngress?.edgeFilter || [];
@@ -518,6 +521,7 @@ export class OpsViewRoutes extends DeesElement {
<dees-input-text .key=${'targetHost'} .label=${'Target Host'} .description=${'Used when no network target is selected'} .value=${currentTargetHost}></dees-input-text>
<dees-input-text .key=${'targetPort'} .label=${'Target Port'} .description=${'Used when no network target is selected'} .value=${currentTargetPort}></dees-input-text>
<dees-input-checkbox .key=${'preserveMatchPort'} .label=${'Preserve incoming port'} .value=${currentPreserveMatchPort}></dees-input-checkbox>
<dees-input-checkbox .key=${'vpnOnly'} .label=${'VPN only'} .description=${'Only VPN clients with matching target profiles can access this route'} .value=${currentVpnOnly}></dees-input-checkbox>
<dees-input-checkbox .key=${'remoteIngressEnabled'} .label=${'Enable Remote Ingress'} .value=${currentRemoteIngressEnabled}></dees-input-checkbox>
<div class="remoteIngressGroup" style="display: ${currentRemoteIngressEnabled ? 'flex' : 'none'}; flex-direction: column; gap: 16px;">
<dees-input-list .key=${'remoteIngressEdgeFilter'} .label=${'Edge Filter'} .description=${'Optional edge IDs or tags. Leave empty to allow all edges.'} .placeholder=${'Add edge ID or tag...'} .value=${currentEdgeFilter}></dees-input-list>
@@ -570,6 +574,7 @@ export class OpsViewRoutes extends DeesElement {
const remoteIngressEdgeFilter: string[] = Array.isArray(formData.remoteIngressEdgeFilter)
? formData.remoteIngressEdgeFilter.filter(Boolean)
: [];
const vpnOnly = Boolean(formData.vpnOnly);
const updatedRoute: any = {
name: formData.name,
@@ -586,6 +591,7 @@ export class OpsViewRoutes extends DeesElement {
},
],
},
vpnOnly: vpnOnly ? true : null,
remoteIngress: remoteIngressEnabled
? {
enabled: true,
@@ -684,6 +690,7 @@ export class OpsViewRoutes extends DeesElement {
<dees-input-text .key=${'targetHost'} .label=${'Target Host'} .description=${'Used when no network target is selected'} .value=${'localhost'}></dees-input-text>
<dees-input-text .key=${'targetPort'} .label=${'Target Port'} .description=${'Used when no network target is selected'}></dees-input-text>
<dees-input-checkbox .key=${'preserveMatchPort'} .label=${'Preserve incoming port'} .value=${false}></dees-input-checkbox>
<dees-input-checkbox .key=${'vpnOnly'} .label=${'VPN only'} .description=${'Only VPN clients with matching target profiles can access this route'} .value=${false}></dees-input-checkbox>
<dees-input-checkbox .key=${'remoteIngressEnabled'} .label=${'Enable Remote Ingress'} .value=${false}></dees-input-checkbox>
<div class="remoteIngressGroup" style="display: none; flex-direction: column; gap: 16px;">
<dees-input-list .key=${'remoteIngressEdgeFilter'} .label=${'Edge Filter'} .description=${'Optional edge IDs or tags. Leave empty to allow all edges.'} .placeholder=${'Add edge ID or tag...'}></dees-input-list>
@@ -736,6 +743,7 @@ export class OpsViewRoutes extends DeesElement {
const remoteIngressEdgeFilter: string[] = Array.isArray(formData.remoteIngressEdgeFilter)
? formData.remoteIngressEdgeFilter.filter(Boolean)
: [];
const vpnOnly = Boolean(formData.vpnOnly);
const route: any = {
name: formData.name,
@@ -752,6 +760,7 @@ export class OpsViewRoutes extends DeesElement {
},
],
},
...(vpnOnly ? { vpnOnly: true } : {}),
...(remoteIngressEnabled
? {
remoteIngress: {
+1 -3
View File
@@ -426,9 +426,7 @@ export class OpsDashboard extends DeesElement {
<dees-input-checkbox
.key=${'enableIdpGlobalAuth'}
.label=${'Allow idp.global login for this email'}
.description=${statusArg.idpGlobalConfigured
? 'The local account remains authoritative; idp.global only verifies identity.'
: 'Requires DCROUTER_IDP_GLOBAL_URL before idp.global logins can work.'}
.description=${'Uses https://idp.global by default; the local dcrouter account and role remain authoritative.'}
></dees-input-checkbox>
</dees-form>
</div>