Este documento apresenta a proposta técnica para o desenvolvimento do Middleware NIVEA, uma camada de integração que conecta o sistema de Recursos Humanos CESLA (Hive) ao sistema de controle de acesso físico HikCentral Professional 3.0.1.
This document presents the technical proposal for the development of the NIVEA Middleware, an integration layer connecting the CESLA (Hive) Human Resources system to the HikCentral Professional 3.0.1 physical access control system.
O objetivo é eliminar o processo manual de concessão e revogação de permissões de acesso físico, substituindo-o por uma automação em tempo real baseada no status do colaborador no sistema de RH.
The goal is to eliminate the manual process of granting and revoking physical access permissions, replacing it with real-time automation based on the employee's status in the HR system.
Automação Total
Full Automation
Elimina o trabalho manual de gerenciamento de acessos no HikCentral
Eliminates manual access management work in HikCentral
Tempo Real
Real-Time
Acesso concedido ou revogado automaticamente ao mudar status no RH
Access granted or revoked automatically when HR status changes
Auditoria Completa
Full Audit Trail
Dashboard web com registro detalhado de cada operação realizada
Web dashboard with detailed record of every operation performed
Segurança Reforçada
Enhanced Security
Comunicação criptografada ponta a ponta via IPSec e HMAC-SHA256
End-to-end encrypted communication via IPSec and HMAC-SHA256
Atualmente, quando ocorre uma alteração no status de um colaborador no sistema CESLA (admissão, desligamento, mudança de cargo, inaptidão), a equipe responsável precisa manualmente refletir essa alteração no sistema de controle de acesso HikCentral.
Currently, when a change occurs in an employee's status in the CESLA system (hiring, termination, role change, unfitness), the responsible team needs to manually reflect this change in the HikCentral access control system.
- Atraso entre a decisão de RH e a efetivação no acesso físicoDelay between the HR decision and physical access enforcement
- Risco de segurança quando desligamentos não são refletidos imediatamenteSecurity risk when terminations are not reflected immediately
- Erro humano na concessão ou revogação de permissõesHuman error in granting or revoking permissions
- Falta de rastreabilidade sobre quem autorizou cada alteraçãoLack of traceability about who authorized each change
- Sobrecarga operacional da equipe de segurança/TIOperational overload on the security/IT team
CESLA
Sistema de RH
(Hive / Azure)
HR System
(Hive / Azure)
MIDDLEWARE NIVEA
Node.js + Express
PM2 + SQLite
Dashboard React
HikCentral
Professional 3.0.1
172.16.32.118
O Middleware NIVEA opera como uma camada intermediária inteligente que:
The NIVEA Middleware operates as an intelligent intermediary layer that:
- Recebe dados de colaboradores do CESLA (via webhook e/ou polling periódico)Receives employee data from CESLA (via webhook and/or periodic polling)
- Processa as alterações identificando admissões, atualizações e desligamentosProcesses changes by identifying hires, updates, and terminations
- Executa as ações correspondentes no HikCentral (cadastro, atualização, revogação)Executes the corresponding actions in HikCentral (registration, update, revocation)
- Registra cada operação em banco de dados para auditoria completaRecords each operation in the database for full audit trail
- Disponibiliza uma dashboard web para monitoramento em tempo realProvides a web dashboard for real-time monitoring
Stack TecnológicaTechnology Stack
| Componente | Tecnologia | Justificativa |
|---|---|---|
| Runtime | Node.js 20 LTS | Ecossistema maduro, async nativo |
| Framework | Express.js | Leve, flexível, amplamente adotado |
| Process Manager | PM2 | Auto-restart, clustering, métricas |
| Banco de Dados | SQLite | Sem servidor extra, auditoria local |
| Frontend | React + Vite + Tailwind | SPA moderna e responsiva |
| VPN | StrongSwan (IPSec) | Túnel site-to-site robusto |
| Logs | Winston | Logs estruturados com rotação |
| Component | Technology | Rationale |
|---|---|---|
| Runtime | Node.js 20 LTS | Mature ecosystem, native async |
| Framework | Express.js | Lightweight, flexible, widely adopted |
| Process Manager | PM2 | Auto-restart, clustering, metrics |
| Database | SQLite | No extra server, local audit |
| Frontend | React + Vite + Tailwind | Modern, responsive SPA |
| VPN | StrongSwan (IPSec) | Robust site-to-site tunnel |
| Logs | Winston | Structured logs with rotation |
4.1 — Admissao de Colaborador4.1 — Employee Admission
- CESLA notifica o middleware sobre novo colaborador com status "Apto"CESLA notifies the middleware about a new employee with "Fit" status
- Middleware consulta tabela de mapeamento: cargo → grupo de acessoMiddleware queries the mapping table: role → access group
- Verifica se a pessoa ja existe no HikCentral (busca por CPF)Checks if the person already exists in HikCentral (search by CPF)
- Cadastra a pessoa no HikCentral e adiciona ao grupo de acesso do cargoRegisters the person in HikCentral and adds to the role's access group
- Registra operação no banco de auditoria e atualiza a dashboardRecords the operation in the audit database and updates the dashboard
4.2 — Desligamento / Inaptidao4.2 — Termination / Unfitness
- CESLA notifica mudança de status para "Inapto" ou condicao de desligamentoCESLA notifies status change to "Unfit" or termination condition
- Middleware identifica a mudança de statusMiddleware identifies the status change
- Remove a pessoa de TODOS os grupos de acesso no HikCentralRemoves the person from ALL access groups in HikCentral
- Atualiza validade da pessoa (expira imediatamente)Updates person validity (expires immediately)
- Registra revogação no banco de auditoriaRecords revocation in the audit database
4.3 — Mudanca de Cargo4.3 — Role Change
- Middleware detecta alteração no campo de cargo do colaboradorMiddleware detects a change in the employee's role field
- Remove a pessoa do grupo de acesso anteriorRemoves the person from the previous access group
- Adiciona ao novo grupo de acesso correspondente ao novo cargoAdds to the new access group corresponding to the new role
- Atualiza dados pessoais no HikCentral e registra no banco de auditoriaUpdates personal data in HikCentral and records in the audit database
4.4 — Reconciliação Automática Diária4.4 — Daily Automatic Reconciliation
O middleware inclui uma dashboard web completa para monitoramento e gestao, acessível apenas por administradores autorizados via login com email e senha.
The middleware includes a complete web dashboard for monitoring and management, accessible only by authorized administrators via email and password login.
5.1 — Visualização da Dashboard Principal5.1 — Main Dashboard View
| Horario | Time | Colaborador | Employee | Operacao | Operation | Status |
|---|---|---|---|---|---|---|
| 12:45 | Joao Silva | CREATE | SUCCESS | |||
| 12:42 | Maria Santos | UPDATE | SUCCESS | |||
| 12:40 | Pedro Oliveira | REVOKE | SUCCESS | |||
| 12:38 | Ana Costa | CREATE | ERROR |
5.2 — Telas Disponiveis5.2 — Available Screens
| Tela | Funcionalidades |
|---|---|
| Dashboard Principal | Contadores em tempo real, grafico de operações (7 dias), feed de atividades, status dos sistemas |
| Logs de Auditoria | Tabela paginada com filtros (data, tipo, status, CPF), exportação CSV, detalhes expandiveis |
| Colaboradores | Lista completa com busca, status atual, grupos de acesso, histórico individual |
| Mapeamento de Cargos | CRUD para mapear cargos do CESLA → grupos de acesso HikCentral |
| Configurações | Status dos serviços, sincronização manual, resultado da reconciliação, uptime |
| Screen | Features |
|---|---|
| Main Dashboard | Real-time counters, operations chart (7 days), activity feed, system status |
| Audit Logs | Paginated table with filters (date, type, status, CPF), CSV export, expandable details |
| Employees | Full list with search, current status, access groups, individual history |
| Role Mapping | CRUD to map CESLA roles → HikCentral access groups |
| Settings | Service status, manual sync, reconciliation result, uptime |
5.3 — Segurança da Dashboard5.3 — Dashboard Security
Autenticação
Authentication
Login com email/senha, criptografia bcrypt (salt rounds: 12)
Email/password login, bcrypt encryption (salt rounds: 12)
Sessoes JWT
JWT Sessions
Tokens com expiração de 8 horas, invalidação no logout
Tokens with 8-hour expiration, invalidation on logout
Anti Brute-Force
Rate limiting: 5 tentativas / 15 min, lockout temporário
Rate limiting: 5 attempts / 15 min, temporary lockout
HTTPS + Headers
TLS 1.2+ obrigatório, Helmet.js para headers de segurança
TLS 1.2+ required, Helmet.js for security headers
6.1 — Campos Sincronizados6.1 — Synchronized Fields
| Dado do Colaborador | Origem (CESLA) | Destino (HikCentral) | Transformação |
|---|---|---|---|
| CPF | documentNumber_CPF | personCode | Remove pontuação |
| Nome | name | personGivenName | Primeiro nome |
| Sobrenome | name | personFamilyName | Ultimo sobrenome |
| Genero | gender | gender | M→1, F→2, outro→0 |
| Celular | cellphone | phoneNo | Direto |
mail | email | Direto | |
| Data de admissão | admissionDate | beginTime | ISO 8601 |
| Validade | condition + status | endTime | Apto: futuro / Inapto: atual |
| Cargo | roleCode | Grupo de acesso | Via tabela de mapeamento |
| Employee Data | Source (CESLA) | Destination (HikCentral) | Transformation |
|---|---|---|---|
| CPF (Tax ID) | documentNumber_CPF | personCode | Remove punctuation |
| First Name | name | personGivenName | First name |
| Last Name | name | personFamilyName | Last surname |
| Gender | gender | gender | M→1, F→2, other→0 |
| Mobile | cellphone | phoneNo | Direct |
mail | email | Direct | |
| Admission Date | admissionDate | beginTime | ISO 8601 |
| Validity | condition + status | endTime | Fit: future / Unfit: current |
| Role | roleCode | Access Group | Via mapping table |
6.2 — Regra de Qualificação6.2 — Qualification Rule
status ("Apto" / "Inapto"), sem verificar cada requisito individualmente.
CESLA already internally consolidates the fitness verification, evaluating: valid OSH certificate, up-to-date training, security integration, and company status. The middleware uses only the consolidated status field ("Fit" / "Unfit"), without checking each requirement individually.
6.3 — Mapeamento de Grupos de Acesso6.3 — Access Group Mapping
Os grupos de acesso no HikCentral são determinados pelo cargo (role) do colaborador no CESLA. O mapeamento e configurável via dashboard, sem alteração no código:
Access groups in HikCentral are determined by the employee's role in CESLA. The mapping is configurable via dashboard, without code changes:
| Cargo no CESLA | → | Grupo de Acesso HikCentral |
|---|---|---|
| Operador de Produção | → | Acesso Area Produtiva |
| Analista Administrativo | → | Acesso Escritorios |
| Gerente de Area | → | Acesso Total |
| (exemplos ilustrativos — configuração real feita via dashboard) | ||
| CESLA Role | → | HikCentral Access Group |
|---|---|---|
| Production Operator | → | Production Area Access |
| Administrative Analyst | → | Office Access |
| Area Manager | → | Full Access |
| (illustrative examples — actual configuration done via dashboard) | ||
7.1 — Camadas de Proteção7.1 — Protection Layers
| Comunicação | Protocolo | Mecanismo |
|---|---|---|
| CESLA → Middleware | HTTPS (TLS 1.2+) | Autenticação JWT, validação de IP |
| Middleware → HikCentral | IPSec ESP (AES-256) | Túnel VPN + HMAC-SHA256 por requisição |
| Dashboard (Browser) | HTTPS (TLS 1.2+) | JWT + bcrypt + rate limiting |
| Credenciais | — | Variáveis de ambiente, nunca no código |
| Banco de dados | — | Permissões de arquivo restritas (640) |
| HikCentral | Rede privada | Não exposto a internet, apenas via VPN |
| Dados sensíveis | — | CPF mascarado nos logs de auditoria |
| Communication | Protocol | Mechanism |
|---|---|---|
| CESLA → Middleware | HTTPS (TLS 1.2+) | JWT Authentication, IP validation |
| Middleware → HikCentral | IPSec ESP (AES-256) | VPN Tunnel + HMAC-SHA256 per request |
| Dashboard (Browser) | HTTPS (TLS 1.2+) | JWT + bcrypt + rate limiting |
| Credentials | — | Environment variables, never in code |
| Database | — | Restricted file permissions (640) |
| HikCentral | Private network | Not exposed to internet, VPN only |
| Sensitive data | — | CPF masked in audit logs |
7.2 — Túnel VPN (IPSec)7.2 — VPN Tunnel (IPSec)
7.3 — Autenticação HikCentral (HMAC-SHA256)7.3 — HikCentral Authentication (HMAC-SHA256)
Cada requisição ao HikCentral inclui uma assinatura digital calculada com AppKey e AppSecret:
Each request to HikCentral includes a digital signature calculated with AppKey and AppSecret:
8.1 — Servidor (VPS)8.1 — Server (VPS)
| Específicação | Valor |
|---|---|
| vCPU | 2 nucleos |
| RAM | 8 GB |
| Disco | 100 GB NVMe |
| Bandwidth | 8 TB |
| Sistema Operacional | Ubuntu 22.04 LTS |
| Specification | Value |
|---|---|
| vCPU | 2 cores |
| RAM | 8 GB |
| Disk | 100 GB NVMe |
| Bandwidth | 8 TB |
| Operating System | Ubuntu 22.04 LTS |
O projeto será executado nas seguintes fases de implementação:
The project will be executed in the following implementation phases:
- Infraestrutura — Provisionar servidor, instalar Node.js/PM2/StrongSwan, configurar túnel IPSec e firewall, testar conectividade com HikCentralInfrastructure — Provision server, install Node.js/PM2/StrongSwan, configure IPSec tunnel and firewall, test connectivity with HikCentral
- Integração HikCentral — Módulo HMAC-SHA256, client HikCentral, testes de cada endpoint (cadastro, atualização, grupo de acesso)HikCentral Integration — HMAC-SHA256 module, HikCentral client, testing each endpoint (registration, update, access group)
- Integração CESLA — Autenticação JWT, polling periódico, endpoint webhook, mapeamento de camposCESLA Integration — JWT authentication, periodic polling, webhook endpoint, field mapping
- Lógica de Negócio — Sincronização automática, fluxos de criação/atualização/revogação, reconciliação diária, deduplicaçãoBusiness Logic — Automatic synchronization, create/update/revoke flows, daily reconciliation, deduplication
- Dashboard de Auditoria — Interface React completa: login, dashboard principal, logs, colaboradores, mapeamentos, configuraçõesAudit Dashboard — Complete React interface: login, main dashboard, logs, employees, mappings, settings
- Hardening e Go-Live — Segurança (rate limit, helmet, CORS), testes end-to-end, documentação operacional, deploy finalHardening & Go-Live — Security (rate limit, helmet, CORS), end-to-end testing, operational documentation, final deploy
Para viabilizar o projeto, a Nivea precisa fornecer os seguintes itens:
To enable the project, Nivea needs to provide the following items:
| Item | Responsavel | Status |
|---|---|---|
| AppKey e AppSecret do HikCentral OpenAPI | TI Nivea | ☐ Pendente |
| Credenciais CESLA (usuario e senha da API) | Gestao CESLA | ☐ Pendente |
| Configuração VPN (PSK ou certificado X.509) | TI Nivea / Rede | ☐ Pendente |
| IP privado autorizado no firewall | TI Nivea / Rede | ☐ Pendente |
| Lista de grupos de acesso do HikCentral | Segurança Nivea | ☐ Pendente |
| Mapeamento cargo → grupo de acesso | RH + Segurança | ☐ Pendente |
| Confirmação do orgIndexCode (HikCentral) | TI Nivea | ☐ Pendente |
| Ativação de webhook no CESLA (opcional) | Gestao CESLA | ☐ Pendente |
| Item | Responsible | Status |
|---|---|---|
| HikCentral OpenAPI AppKey and AppSecret | Nivea IT | ☐ Pending |
| CESLA Credentials (API username and password) | CESLA Management | ☐ Pending |
| VPN Configuration (PSK or X.509 certificate) | Nivea IT / Network | ☐ Pending |
| Authorized private IP on the firewall | Nivea IT / Network | ☐ Pending |
| List of HikCentral access groups | Nivea Security | ☐ Pending |
| Role → access group mapping | HR + Security | ☐ Pending |
| orgIndexCode confirmation (HikCentral) | Nivea IT | ☐ Pending |
| CESLA webhook activation (optional) | CESLA Management | ☐ Pending |
O sistema é projetado para resiliência e auto-recuperação:
The system is designed for resilience and self-recovery:
| Cenário de Falha | Comportamento do Middleware |
|---|---|
| CESLA offline | Retry automático com backoff exponencial (3 tentativas) |
| HikCentral offline | Retry automático, operações pendentes registradas no banco |
| Túnel VPN caído | Alerta na dashboard, operações suspensas até restabelecimento |
| Dados duplicados | Deduplicação automática por hash do payload |
| Cargo sem mapeamento | Alerta na dashboard, acesso não concedido até configuração |
| Divergência na reconciliação | Correção automática + relatório detalhado |
| Failure Scenário | Middleware Behavior |
|---|---|
| CESLA offline | Automatic retry with exponential backoff (3 attempts) |
| HikCentral offline | Automatic retry, pending operations recorded in database |
| VPN tunnel down | Dashboard alert, operations suspended until restored |
| Duplicate data | Automatic deduplication by payload hash |
| Unmapped role | Dashboard alert, access not granted until configured |
| Reconciliation discrepancy | Automatic correction + detailed report |
- Avaliação interna deste documento pela equipe de TI e Segurança da NiveaInternal review of this document by the Nivea IT and Security team
- Fornecimento dos pre-requisitos listados na Seção 10Provision of the prerequisites listed in Section 10
- Definição do mapeamento cargo → grupo de acesso (RH + Segurança)Define the role → access group mapping (HR + Security)
- Início da implementação conforme cronograma da Seção 9Start implementation according to Section 9 timeline