@brandazm/dynamic-permissions
Version:
A flexible and powerful permissions management system for NestJS applications with built-in security features
170 lines • 9.77 kB
JavaScript
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConfigPublisherService = void 0;
const common_1 = require("@nestjs/common");
const default_config_1 = require("../config/default-config");
const default_security_config_1 = require("../config/default-security.config");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
let ConfigPublisherService = class ConfigPublisherService {
constructor() {
this.templates = {
basic: {
name: 'Basic Configuration',
description: 'Basic configuration with essential features',
config: default_config_1.defaultConfig,
},
strict: {
name: 'Strict Configuration',
description: 'Enhanced configuration with stricter settings',
config: Object.assign(Object.assign({}, default_config_1.defaultConfig), { security: Object.assign(Object.assign({}, default_security_config_1.defaultSecurityConfig), { rateLimit: {
enabled: true,
windowMs: 15 * 60 * 1000,
max: 50,
}, cors: {
enabled: true,
allowedOrigins: [],
allowedMethods: ['GET', 'POST'],
allowedHeaders: ['Content-Type', 'Authorization'],
exposedHeaders: [],
credentials: true,
}, helmet: Object.assign(Object.assign({}, default_security_config_1.defaultSecurityConfig.helmet), { contentSecurityPolicy: true, crossOriginEmbedderPolicy: true, hsts: true }), requestValidation: {
maxBodySize: 5 * 1024 * 1024,
requireJsonContent: true,
validateContentType: true,
}, enableCaching: true, cacheTimeout: 1800, enableAuditLog: true }) }),
},
enterprise: {
name: 'Enterprise Configuration',
description: 'Full-featured configuration for enterprise applications',
config: Object.assign(Object.assign({}, default_config_1.defaultConfig), { security: Object.assign(Object.assign({}, default_security_config_1.defaultSecurityConfig), { rateLimit: {
enabled: true,
windowMs: 5 * 60 * 1000,
max: 100,
}, cors: {
enabled: true,
allowedOrigins: [],
allowedMethods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Custom-Header'],
exposedHeaders: ['X-Total-Count', 'X-Rate-Limit'],
credentials: true,
}, helmet: {
enabled: true,
contentSecurityPolicy: true,
crossOriginEmbedderPolicy: true,
crossOriginOpenerPolicy: true,
crossOriginResourcePolicy: true,
dnsPrefetchControl: true,
frameguard: true,
hidePoweredBy: true,
hsts: true,
ieNoOpen: true,
noSniff: true,
referrerPolicy: true,
xssFilter: true,
}, requestValidation: {
maxBodySize: 10 * 1024 * 1024,
requireJsonContent: true,
validateContentType: true,
}, enableCaching: true, cacheTimeout: 7200, enableAuditLog: true }) }),
},
};
}
async publishConfigToProject(projectPath, template = 'basic', customizations) {
if (!this.templates[template]) {
throw new Error(`Template "${template}" not found`);
}
const configDir = path.join(projectPath, 'config');
if (!fs.existsSync(configDir)) {
fs.mkdirSync(configDir, { recursive: true });
}
const baseConfig = this.templates[template].config;
const finalConfig = customizations ? this.mergeConfigs(baseConfig, customizations) : baseConfig;
const configPath = path.join(configDir, 'permissions.config.ts');
const configContent = this.generateConfigFile(finalConfig);
fs.writeFileSync(configPath, configContent, 'utf8');
}
async updateProjectConfig(projectPath, updates) {
const configPath = path.join(projectPath, 'config', 'permissions.config.ts');
if (!fs.existsSync(configPath)) {
throw new Error('Configuration file not found');
}
const currentConfig = await Promise.resolve(`${configPath}`).then(s => __importStar(require(s)));
const updatedConfig = this.mergeConfigs(currentConfig, updates);
const configContent = this.generateConfigFile(updatedConfig);
fs.writeFileSync(configPath, configContent, 'utf8');
}
getAvailableTemplates() {
return Object.values(this.templates);
}
mergeConfigs(base, updates) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
return {
database: Object.assign(Object.assign(Object.assign({}, base.database), updates.database), { entities: {
permissions: Object.assign(Object.assign({}, (_b = (_a = base.database) === null || _a === void 0 ? void 0 : _a.entities) === null || _b === void 0 ? void 0 : _b.permissions), (_d = (_c = updates.database) === null || _c === void 0 ? void 0 : _c.entities) === null || _d === void 0 ? void 0 : _d.permissions),
routerPermissions: Object.assign(Object.assign({}, (_f = (_e = base.database) === null || _e === void 0 ? void 0 : _e.entities) === null || _f === void 0 ? void 0 : _f.routerPermissions), (_h = (_g = updates.database) === null || _g === void 0 ? void 0 : _g.entities) === null || _h === void 0 ? void 0 : _h.routerPermissions),
userPermissions: Object.assign(Object.assign({}, (_k = (_j = base.database) === null || _j === void 0 ? void 0 : _j.entities) === null || _k === void 0 ? void 0 : _k.userPermissions), (_m = (_l = updates.database) === null || _l === void 0 ? void 0 : _l.entities) === null || _m === void 0 ? void 0 : _m.userPermissions),
} }),
permissions: Object.assign(Object.assign(Object.assign({}, base.permissions), updates.permissions), { publicRoutes: [
...(((_o = base.permissions) === null || _o === void 0 ? void 0 : _o.publicRoutes) || []),
...(((_p = updates.permissions) === null || _p === void 0 ? void 0 : _p.publicRoutes) || []),
] }),
security: Object.assign(Object.assign({}, base.security), updates.security),
};
}
generateConfigFile(config) {
const configStr = JSON.stringify(config, null, 2);
return `export const config = ${configStr}`;
}
writeConfigToFile(config, filePath) {
const configDir = path.dirname(filePath);
if (!fs.existsSync(configDir)) {
fs.mkdirSync(configDir, { recursive: true });
}
fs.writeFileSync(filePath, JSON.stringify(config, null, 2));
}
};
exports.ConfigPublisherService = ConfigPublisherService;
exports.ConfigPublisherService = ConfigPublisherService = __decorate([
(0, common_1.Injectable)()
], ConfigPublisherService);
//# sourceMappingURL=config-publisher.service.js.map