feat(api): permisos de menú en SQLite con API de administración
- SQLite (better-sqlite3 + TypeORM, WAL) con tabla menu_permissions (usuario web, patrón de ruta); archivo fuera del repo. - GET /api/user/menu para el frontend; GET/PUT/DELETE /api/permissions solo para administradores (acceso "*"). - ADMIN_WEB_USERS garantiza el acceso total al arrancar; no se puede quitar el "*" al último administrador (409, dentro de una transacción). - Patrones validados (`*`, `/modulo/ruta`, `/modulo/*`). A diferencia del frontend anterior, `/inventario/*` ya no habilita `/inventario-x`. - Helper de e2e compartido (SAP simulado, SQLite en memoria). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
079cedbaed
commit
73fffee2f7
19 files changed
+1104
-55
No files matched your search
@@ -1,11 +1,13 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuthModule } from './auth/auth.module.js';
|
||||
import { AppConfigModule } from './config/config.module.js';
|
||||
import { DatabaseModule } from './database/database.module.js';
|
||||
import { HealthController } from './health/health.controller.js';
|
||||
import { PermissionsModule } from './permissions/permissions.module.js';
|
||||
import { SapModule } from './sap/sap.module.js';
|
||||
|
||||
@Module({
|
||||
imports: [AppConfigModule, SapModule, AuthModule],
|
||||
imports: [AppConfigModule, DatabaseModule, SapModule, AuthModule, PermissionsModule],
|
||||
controllers: [HealthController],
|
||||
})
|
||||
export class AppModule {}
|
||||
@@ -16,6 +16,12 @@ describe('validateEnv', () => {
|
||||
expect(env.SAPB1_SL_VERIFY_SSL).toBe(true);
|
||||
expect(env.SAPB1_SL_CA_FILE).toBeUndefined();
|
||||
expect(env.SAPB1_SL_MAX_CONCURRENCY).toBe(1);
|
||||
expect(env.SQLITE_PATH).toBe('./data/app.sqlite');
|
||||
expect(env.ADMIN_WEB_USERS).toEqual([]);
|
||||
});
|
||||
|
||||
it('separa ADMIN_WEB_USERS', () => {
|
||||
expect(validateEnv({ ...sap, ADMIN_WEB_USERS: 'george, ana ,' }).ADMIN_WEB_USERS).toEqual(['george', 'ana']);
|
||||
});
|
||||
|
||||
it('quita la barra final de la URL de SAP', () => {
|
||||
|
||||
@@ -19,6 +19,19 @@ export const envSchema = z
|
||||
.filter(Boolean),
|
||||
),
|
||||
LOG_LEVEL: z.enum(['error', 'warn', 'log', 'debug', 'verbose']).default('log'),
|
||||
// Base SQLite local (permisos de menú). `:memory:` para pruebas.
|
||||
SQLITE_PATH: z.string().min(1).default('./data/app.sqlite'),
|
||||
// Usuarios web (U_WEB_USER) que siempre tienen acceso total ("*"); se
|
||||
// garantiza al arrancar para no quedar fuera por un error de permisos.
|
||||
ADMIN_WEB_USERS: z
|
||||
.string()
|
||||
.default('')
|
||||
.transform((v) =>
|
||||
v
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean),
|
||||
),
|
||||
// Inactividad tras la cual caduca la sesión web (deslizante).
|
||||
SESSION_TIMEOUT_MINUTES: z.coerce.number().int().positive().default(30),
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { mkdirSync } from 'node:fs';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { AppConfigService } from '../config/app-config.service.js';
|
||||
|
||||
/** Base SQLite local de la aplicación (hoy: permisos de menú). */
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forRootAsync({
|
||||
inject: [AppConfigService],
|
||||
useFactory: (config: AppConfigService) => {
|
||||
const database = config.get('SQLITE_PATH');
|
||||
const inMemory = database === ':memory:';
|
||||
if (!inMemory) mkdirSync(dirname(resolve(database)), { recursive: true });
|
||||
return {
|
||||
type: 'better-sqlite3' as const,
|
||||
database,
|
||||
enableWAL: !inMemory,
|
||||
autoLoadEntities: true,
|
||||
// Una sola tabla pequeña: el esquema se sincroniza solo. Cuando el
|
||||
// esquema se estabilice por cliente, pasar a migraciones.
|
||||
synchronize: true,
|
||||
};
|
||||
},
|
||||
}),
|
||||
],
|
||||
})
|
||||
export class DatabaseModule {}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { type CanActivate, type ExecutionContext, ForbiddenException, Injectable } from '@nestjs/common';
|
||||
import type { AuthenticatedRequest } from '../auth/auth.types.js';
|
||||
import { PermissionsService } from './permissions.service.js';
|
||||
|
||||
/** Solo usuarios con acceso total ("*"). Se ejecuta después del guard de sesión global. */
|
||||
@Injectable()
|
||||
export class AdminGuard implements CanActivate {
|
||||
constructor(private readonly permissions: PermissionsService) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const req = context.switchToHttp().getRequest<AuthenticatedRequest>();
|
||||
if (!(await this.permissions.isAdmin(req.user.webUser))) {
|
||||
throw new ForbiddenException('Requiere permisos de administrador');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { Column, Entity, PrimaryGeneratedColumn, Unique } from 'typeorm';
|
||||
|
||||
/** Un patrón de ruta permitido para un usuario web (`*`, `/ventas/*`, `/ventas/ordenes`). */
|
||||
@Entity('menu_permissions')
|
||||
@Unique(['webUser', 'pattern'])
|
||||
export class MenuPermission {
|
||||
@PrimaryGeneratedColumn()
|
||||
id: number;
|
||||
|
||||
@Column()
|
||||
webUser: string;
|
||||
|
||||
@Column()
|
||||
pattern: string;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { Body, Controller, Delete, Get, HttpCode, Param, Put, Req, UseGuards } from '@nestjs/common';
|
||||
import { z } from 'zod';
|
||||
import type { AuthenticatedRequest } from '../auth/auth.types.js';
|
||||
import { ZodValidationPipe } from '../common/zod-validation.pipe.js';
|
||||
import { AdminGuard } from './admin.guard.js';
|
||||
import { PermissionsService } from './permissions.service.js';
|
||||
|
||||
// `*`, `/ventas/ordenes` o `/ventas/*`
|
||||
const pathPattern = z
|
||||
.string()
|
||||
.max(100)
|
||||
.regex(/^(\*|(\/[A-Za-z0-9_-]+)+(\/\*)?)$/, 'Patrón inválido: use "*", "/modulo/ruta" o "/modulo/*"');
|
||||
const setPathsSchema = z.object({ paths: z.array(pathPattern).max(200) });
|
||||
const webUserSchema = z.string().trim().min(1).max(100);
|
||||
type SetPathsDto = z.infer<typeof setPathsSchema>;
|
||||
|
||||
/** Menú permitido para el usuario de la sesión (lo consume el frontend). */
|
||||
@Controller('user')
|
||||
export class UserMenuController {
|
||||
constructor(private readonly permissions: PermissionsService) {}
|
||||
|
||||
@Get('menu')
|
||||
async menu(@Req() req: AuthenticatedRequest) {
|
||||
return { allowedPaths: await this.permissions.getPaths(req.user.webUser) };
|
||||
}
|
||||
}
|
||||
|
||||
/** Administración de permisos (solo acceso total). */
|
||||
@Controller('permissions')
|
||||
@UseGuards(AdminGuard)
|
||||
export class PermissionsController {
|
||||
constructor(private readonly permissions: PermissionsService) {}
|
||||
|
||||
@Get()
|
||||
list() {
|
||||
return this.permissions.listAll();
|
||||
}
|
||||
|
||||
@Get(':webUser')
|
||||
async get(@Param('webUser', new ZodValidationPipe(webUserSchema)) webUser: string) {
|
||||
return { webUser, paths: await this.permissions.getPaths(webUser) };
|
||||
}
|
||||
|
||||
@Put(':webUser')
|
||||
set(
|
||||
@Param('webUser', new ZodValidationPipe(webUserSchema)) webUser: string,
|
||||
@Body(new ZodValidationPipe(setPathsSchema)) body: SetPathsDto,
|
||||
) {
|
||||
return this.permissions.setPaths(webUser, body.paths);
|
||||
}
|
||||
|
||||
@Delete(':webUser')
|
||||
@HttpCode(204)
|
||||
remove(@Param('webUser', new ZodValidationPipe(webUserSchema)) webUser: string) {
|
||||
return this.permissions.remove(webUser);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { AdminGuard } from './admin.guard.js';
|
||||
import { MenuPermission } from './menu-permission.entity.js';
|
||||
import { PermissionsController, UserMenuController } from './permissions.controller.js';
|
||||
import { PermissionsService } from './permissions.service.js';
|
||||
|
||||
@Module({
|
||||
imports: [TypeOrmModule.forFeature([MenuPermission])],
|
||||
controllers: [UserMenuController, PermissionsController],
|
||||
providers: [PermissionsService, AdminGuard],
|
||||
exports: [PermissionsService],
|
||||
})
|
||||
export class PermissionsModule {}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { ConflictException } from '@nestjs/common';
|
||||
import { DataSource } from 'typeorm';
|
||||
import type { AppConfigService } from '../config/app-config.service.js';
|
||||
import { MenuPermission } from './menu-permission.entity.js';
|
||||
import { PermissionsService } from './permissions.service.js';
|
||||
|
||||
describe('PermissionsService (SQLite en memoria)', () => {
|
||||
let ds: DataSource;
|
||||
let service: PermissionsService;
|
||||
|
||||
beforeEach(async () => {
|
||||
ds = new DataSource({ type: 'better-sqlite3', database: ':memory:', entities: [MenuPermission], synchronize: true });
|
||||
await ds.initialize();
|
||||
service = new PermissionsService(ds.getRepository(MenuPermission), { get: () => [] } as unknown as AppConfigService);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await ds.destroy();
|
||||
});
|
||||
|
||||
it('setPaths reemplaza y quita duplicados', async () => {
|
||||
await service.setPaths('luis', ['/ventas/*', '/compras/*']);
|
||||
await service.setPaths('luis', ['/inventario/*', '/inventario/*']);
|
||||
expect(await service.getPaths('luis')).toEqual(['/inventario/*']);
|
||||
});
|
||||
|
||||
it('listAll agrupa por usuario', async () => {
|
||||
await service.setPaths('b', ['/x']);
|
||||
await service.setPaths('a', ['/z', '/y']);
|
||||
expect(await service.listAll()).toEqual([
|
||||
{ webUser: 'a', paths: ['/y', '/z'] },
|
||||
{ webUser: 'b', paths: ['/x'] },
|
||||
]);
|
||||
});
|
||||
|
||||
it('ensureAdmins es idempotente y conserva otros permisos', async () => {
|
||||
await service.setPaths('ana', ['/ventas/*']);
|
||||
await service.ensureAdmins(['ana', 'ana', 'luis']);
|
||||
await service.ensureAdmins(['ana']);
|
||||
expect(await service.getPaths('ana')).toEqual(['*', '/ventas/*']);
|
||||
expect(await service.isAdmin('luis')).toBe(true);
|
||||
});
|
||||
|
||||
it('protege al último administrador (setPaths y remove)', async () => {
|
||||
await service.ensureAdmins(['ana']);
|
||||
await expect(service.setPaths('ana', ['/ventas/*'])).rejects.toBeInstanceOf(ConflictException);
|
||||
await expect(service.remove('ana')).rejects.toBeInstanceOf(ConflictException);
|
||||
expect(await service.getPaths('ana')).toEqual(['*']); // la transacción no dejó cambios
|
||||
|
||||
await service.ensureAdmins(['luis']);
|
||||
await service.remove('ana');
|
||||
expect(await service.getPaths('ana')).toEqual([]);
|
||||
});
|
||||
|
||||
it('no permite duplicar (usuario, patrón) a nivel de base de datos', async () => {
|
||||
const repo = ds.getRepository(MenuPermission);
|
||||
await repo.insert({ webUser: 'a', pattern: '/x' });
|
||||
await expect(repo.insert({ webUser: 'a', pattern: '/x' })).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import { ConflictException, Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Not, Repository } from 'typeorm';
|
||||
import { AppConfigService } from '../config/app-config.service.js';
|
||||
import { MenuPermission } from './menu-permission.entity.js';
|
||||
|
||||
export const ALL_ACCESS = '*';
|
||||
|
||||
export interface UserPermissions {
|
||||
webUser: string;
|
||||
paths: string[];
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class PermissionsService implements OnApplicationBootstrap {
|
||||
private readonly logger = new Logger(PermissionsService.name);
|
||||
|
||||
constructor(
|
||||
@InjectRepository(MenuPermission) private readonly repo: Repository<MenuPermission>,
|
||||
private readonly config: AppConfigService,
|
||||
) {}
|
||||
|
||||
async onApplicationBootstrap() {
|
||||
await this.ensureAdmins(this.config.get('ADMIN_WEB_USERS'));
|
||||
}
|
||||
|
||||
async getPaths(webUser: string): Promise<string[]> {
|
||||
const rows = await this.repo.find({ where: { webUser }, order: { pattern: 'ASC' } });
|
||||
return rows.map((r) => r.pattern);
|
||||
}
|
||||
|
||||
async listAll(): Promise<UserPermissions[]> {
|
||||
const rows = await this.repo.find({ order: { webUser: 'ASC', pattern: 'ASC' } });
|
||||
const byUser = new Map<string, string[]>();
|
||||
for (const r of rows) byUser.set(r.webUser, [...(byUser.get(r.webUser) ?? []), r.pattern]);
|
||||
return [...byUser].map(([webUser, paths]) => ({ webUser, paths }));
|
||||
}
|
||||
|
||||
async isAdmin(webUser: string): Promise<boolean> {
|
||||
return this.repo.existsBy({ webUser, pattern: ALL_ACCESS });
|
||||
}
|
||||
|
||||
/** Reemplaza todos los permisos del usuario. */
|
||||
async setPaths(webUser: string, paths: string[]): Promise<UserPermissions> {
|
||||
const unique = [...new Set(paths)].sort();
|
||||
await this.repo.manager.transaction(async (manager) => {
|
||||
const repo = manager.getRepository(MenuPermission);
|
||||
if (!unique.includes(ALL_ACCESS)) await this.assertNotLastAdmin(repo, webUser);
|
||||
await repo.delete({ webUser });
|
||||
if (unique.length) await repo.insert(unique.map((pattern) => ({ webUser, pattern })));
|
||||
});
|
||||
this.logger.log(`Permisos de ${webUser} actualizados (${unique.length} patrones)`);
|
||||
return { webUser, paths: unique };
|
||||
}
|
||||
|
||||
async remove(webUser: string): Promise<void> {
|
||||
await this.repo.manager.transaction(async (manager) => {
|
||||
const repo = manager.getRepository(MenuPermission);
|
||||
await this.assertNotLastAdmin(repo, webUser);
|
||||
await repo.delete({ webUser });
|
||||
});
|
||||
this.logger.log(`Permisos de ${webUser} eliminados`);
|
||||
}
|
||||
|
||||
/** Garantiza el acceso total de los administradores configurados en el .env. */
|
||||
async ensureAdmins(webUsers: string[]): Promise<void> {
|
||||
for (const webUser of webUsers) {
|
||||
if (await this.isAdmin(webUser)) continue;
|
||||
await this.repo.insert({ webUser, pattern: ALL_ACCESS });
|
||||
this.logger.log(`Administrador "${webUser}" garantizado desde ADMIN_WEB_USERS`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Evita dejar el sistema sin ningún usuario con acceso total. */
|
||||
private async assertNotLastAdmin(repo: Repository<MenuPermission>, webUser: string) {
|
||||
const isAdminNow = await repo.existsBy({ webUser, pattern: ALL_ACCESS });
|
||||
if (!isAdminNow) return;
|
||||
const others = await repo.countBy({ pattern: ALL_ACCESS, webUser: Not(webUser) });
|
||||
if (others === 0) {
|
||||
throw new ConflictException('No se puede quitar el acceso total al último administrador');
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user