feat: add hotspot admin panel and harden payment provisioning
build-image / build-push (push) Failing after 1m36s
build-image / build-push (push) Failing after 1m36s
This commit is contained in:
1 parent
fb3135d18f
commit
ebb2d1d792
25 files changed
+832
-686
No files matched your search
@@ -0,0 +1,8 @@
|
|||||||
|
# Copy to .env on the Docker host. Never commit real credentials.
|
||||||
|
MIKROTIK_PASSWORD=replace-with-router-api-password
|
||||||
|
ADMIN_TOKEN=replace-with-at-least-32-random-characters
|
||||||
|
MP_ACCESS_TOKEN=COLE_SEU_TOKEN_AQUI
|
||||||
|
MP_ENVIRONMENT=sandbox
|
||||||
|
MP_PUBLIC_KEY=
|
||||||
|
MP_WEBHOOK_SECRET=
|
||||||
|
TRUST_PROXY=
|
||||||
@@ -20,6 +20,20 @@ jobs:
|
|||||||
- name: Setup Buildx
|
- name: Setup Buildx
|
||||||
uses: docker/setup-buildx-action@v3
|
uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
|
- name: Setup Node
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: '22'
|
||||||
|
cache: npm
|
||||||
|
cache-dependency-path: backend/package-lock.json
|
||||||
|
|
||||||
|
- name: Install and test
|
||||||
|
working-directory: backend
|
||||||
|
run: |
|
||||||
|
npm ci
|
||||||
|
npm test
|
||||||
|
npm audit --omit=dev --audit-level=moderate
|
||||||
|
|
||||||
- name: Login no Gitea Container Registry
|
- name: Login no Gitea Container Registry
|
||||||
uses: docker/login-action@v3
|
uses: docker/login-action@v3
|
||||||
with:
|
with:
|
||||||
|
|||||||
@@ -1,412 +1,102 @@
|
|||||||
# pix-hotspot — Wi-Fi Convidados com PIX
|
# INCTG — Wi-Fi com PIX
|
||||||
|
|
||||||
Sistema completo de **Wi-Fi pago para convidados**: hotspot MikroTik + portal de
|
Portal de venda de acesso Wi-Fi integrado ao Mercado Pago (Orders API) e ao hotspot MikroTik. Backend Node.js 22 + Express; interface HTML/CSS/JavaScript; persistência local em JSON.
|
||||||
pagamento com PIX (Mercado Pago) + liberação automática de acesso.
|
|
||||||
|
|
||||||
> **INCTG — Tecnologia que resolve.**
|
## Fluxo
|
||||||
|
|
||||||
```text
|
1. O MikroTik redireciona o convidado para o portal, com `?mac=...`.
|
||||||
Convidado conecta no Wi-Fi "Internet Gratis"
|
2. O backend pode criar uma conta temporária, vinculada ao MAC, para abrir o aplicativo do banco (120 segundos; intervalo mínimo de 300 segundos).
|
||||||
│
|
3. O comprador escolhe o plano, informa nome/e-mail e gera o PIX.
|
||||||
▼
|
4. O pagamento é confirmado consultando a API do Mercado Pago. O webhook assinado antecipa a consulta; há também polling a cada 15 segundos no backend e 6 segundos no portal.
|
||||||
Hotspot MikroTik (captive portal)
|
5. O backend valida referência e valor pago e provisiona um voucher no MikroTik. Repetições reutilizam as credenciais persistidas.
|
||||||
│ abre o portal e escolhe o plano
|
6. O usuário faz login no hotspot. Os limites são de **tempo acumulado de conexão**, não de validade corrida desde a compra.
|
||||||
▼
|
|
||||||
Backend (ZimaOS / Docker) ◄──────► API Mercado Pago (PIX)
|
|
||||||
│ pagamento aprovado (polling 15s)
|
|
||||||
▼
|
|
||||||
Voucher criado automaticamente no MikroTik (API local)
|
|
||||||
│
|
|
||||||
▼
|
|
||||||
Convidado loga no hotspot e usa o Wi-Fi
|
|
||||||
com velocidade e validade do plano contratado
|
|
||||||
```
|
|
||||||
|
|
||||||
**Garantias de projeto**
|
## Instalação Docker
|
||||||
|
|
||||||
- Rede de convidados **totalmente isolada** (`10.10.10.0/24`) — não acessa seus
|
1. Copie `.env.example` para `.env` no host Docker e preencha `MIKROTIK_PASSWORD` e `ADMIN_TOKEN`.
|
||||||
PCs, servidores nem a interface do MikroTik
|
2. Configure `MP_ACCESS_TOKEN`, `BASE_URL`, IP/usuário/servidor MikroTik no `docker-compose.yml`. As credenciais reais devem permanecer exclusivamente no servidor.
|
||||||
- API do MikroTik usada **apenas localmente** (nada exposto à internet)
|
3. Configure `MP_WEBHOOK_SECRET` com a assinatura secreta da aplicação Mercado Pago. Cadastre `https://hotspot.jf.eng.br/api/mp/webhook` para eventos de Orders. Sem esse segredo, o webhook retorna 503 e a confirmação continua por polling.
|
||||||
- Portal de pagamento acessível ao convidado **só na porta 3000**
|
4. Execute `docker compose pull` e `docker compose up -d` após a imagem atualizada estar publicada. Para construir localmente: `docker build -t pix-hotspot-local ./backend` e use essa imagem no Compose.
|
||||||
- Imagem Docker gerada automaticamente pelo **Gitea Actions**
|
5. Verifique `/api/health`, `/api/plans` e um pagamento completo. Health é apenas liveness/configuração do token, não comprova conectividade com Mercado Pago ou roteador.
|
||||||
|
|
||||||
---
|
Gere o token com `node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"`. Ele precisa ter pelo menos 32 caracteres e não pode ser um placeholder iniciado por `troque` ou `dev-token`.
|
||||||
|
|
||||||
## Pré-requisitos
|
A imagem executa como usuário `node` (UID 1000). O diretório `./data` montado em `/app/data` precisa permitir escrita por esse usuário no host Linux. Faça backup de `./data/db.json` antes de atualizar. Esse é o caminho do volume do Compose; não `backend/data`.
|
||||||
|
|
||||||
| Item | Obrigatório | Observação |
|
Use HTTPS no domínio público e mantenha a porta 3000 acessível apenas ao proxy e às redes necessárias. O serviço não configura Cloudflare, DNS ou proxy automaticamente. Se houver proxy reverso, `TRUST_PROXY` deve identificar somente seus IPs/sub-redes confiáveis; sem isso, o limitador considera o IP do proxy. Nunca confie indiscriminadamente em cabeçalhos de clientes.
|
||||||
|------|:-----------:|------------|
|
|
||||||
| MikroTik hAP lite (RB941) ou similar | ✅ | RouterOS 6.43+ (fábrica já atende) |
|
|
||||||
| ZimaOS (ou outro host Linux com Docker) | ✅ | Ligado 24/7, mesma rede do MikroTik |
|
|
||||||
| Conta Mercado Pago vendedora | ✅ | Token de acesso com permissão PIX |
|
|
||||||
| Conta no Gitea (`git.jf.eng.br`) | ✅ | Para versionar e gerar a imagem |
|
|
||||||
| PC com Winbox | ✅ | Configuração inicial do MikroTik |
|
|
||||||
|
|
||||||
---
|
## Painel administrativo
|
||||||
|
|
||||||
## Etapa 1 — Mercado Pago (token PIX)
|
Acesse `https://hotspot.jf.eng.br/admin` **depois de instalar a nova versão** e entre com o `ADMIN_TOKEN`.
|
||||||
|
|
||||||
1. Acesse [mercadopago.com.br](https://www.mercadopago.com.br) e entre na sua conta.
|
- Consultar usuários, perfis, sessões online, MAC/IP, tempo usado e tráfego.
|
||||||
2. **Para testar primeiro (recomendado):** crie uma aplicação em modo
|
- Criar usuário com perfil existente e limite de uso, com senha escolhida ou gerada.
|
||||||
[sandbox](https://www.mercadopago.com.br/developers/pt/docs):
|
- Bloquear/desbloquear; bloquear desativa a conta, encerra sessões e remove cookies.
|
||||||
**Sua conta → Seu negócio → Aplicativos → Criar aplicativo**.
|
- Exportar usuários em CSV UTF-8, sem senhas e com proteção contra fórmulas de planilha.
|
||||||
3. Copie o **Access Token de teste** (começa com `TEST-`).
|
- Consultar os últimos 100 pagamentos e as últimas 100 ações administrativas. O banco conserva até 1000 ações do painel.
|
||||||
4. Quando quiser cobrar de verdade, gere o token de **produção** (começa com
|
|
||||||
`APP_USR-`) na mesma tela.
|
|
||||||
|
|
||||||
> ⚠️ **Regra de ouro:** primeiro rode tudo em `sandbox`. Só troque para
|
O token dá controle administrativo ao portador. É enviado em `x-admin-token`, nunca por URL, e permanece apenas na memória da aba. Recarregar ou sair exige novo login. Trocar `ADMIN_TOKEN` e reiniciar revoga o token anterior. Senhas de usuários novos são mostradas após a criação; o painel não exporta nem lista senhas existentes.
|
||||||
> produção depois de concluir a Etapa 5 com sucesso.
|
|
||||||
|
|
||||||
---
|
Usuários sem servidor específico ou com servidor `all` também aparecem: são contas compartilhadas do roteador e bloqueá-las pode afetar outros hotspots. O histórico registra ações do painel de usuários/exportação; alterações diretas no Winbox não são auditadas pelo backend.
|
||||||
|
|
||||||
## Etapa 2 — Backend no ZimaOS (1 clique)
|
|
||||||
|
|
||||||
### 2.1 Obter o código
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git clone ssh://[email protected]:1080/jfeng/HotSpot.git
|
|
||||||
cd HotSpot
|
|
||||||
```
|
|
||||||
|
|
||||||
Ou baixe o ZIP pelo navegador: `https://git.jf.eng.br/jfeng/HotSpot` → botão
|
|
||||||
**Code → Download ZIP**.
|
|
||||||
|
|
||||||
### 2.2 Editar o `docker-compose.yml`
|
|
||||||
|
|
||||||
Todas as configurações ficam **dentro do próprio compose** — nenhum `.env`
|
|
||||||
extra é necessário. Abra o arquivo e edite:
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
environment:
|
|
||||||
# ===== Mercado Pago (PIX) =====
|
|
||||||
MP_ACCESS_TOKEN: "TEST-..." # ① token da Etapa 1
|
|
||||||
MP_ENVIRONMENT: "sandbox" # ② sandbox | production
|
|
||||||
|
|
||||||
# ===== MikroTik =====
|
|
||||||
MIKROTIK_HOST: "192.168.3.81" # ③ IP atual do hAP lite
|
|
||||||
MIKROTIK_PORT: "8728" # porta padrão da API (não mude)
|
|
||||||
MIKROTIK_USER: "admin" # ④ usuário da API (ver Etapa 3.4)
|
|
||||||
MIKROTIK_PASSWORD: "" # ⑤ senha desse usuário
|
|
||||||
MIKROTIK_SERVER: "guest-hotspot" # ⑥ nome do servidor hotspot
|
|
||||||
|
|
||||||
# ===== Backend =====
|
|
||||||
PORT: "3000"
|
|
||||||
BASE_URL: "http://192.168.3.100:3000" # ⑦ IP do próprio ZimaOS
|
|
||||||
ADMIN_TOKEN: "troque-..." # ⑧ token longo e aleatório
|
|
||||||
```
|
|
||||||
|
|
||||||
| # | Variável | Onde encontrar / regra |
|
|
||||||
|---|----------|------------------------|
|
|
||||||
| ① | `MP_ACCESS_TOKEN` | Mercado Pago → Aplicativos (Etapa 1) |
|
|
||||||
| ② | `MP_ENVIRONMENT` | `sandbox` enquanto testa; `production` no ar |
|
|
||||||
| ③ | `MIKROTIK_HOST` | IP do hAP na rede interna (ex.: `192.168.3.81`). Veja no Winbox: **IP → Addresses** |
|
|
||||||
| ④ | `MIKROTIK_USER` | Use um usuário dedicado (Etapa 3.4), não o `admin` em produção |
|
|
||||||
| ⑤ | `MIKROTIK_PASSWORD` | Senha desse usuário |
|
|
||||||
| ⑥ | `MIKROTIK_SERVER` | Deve ser igual ao nome criado no script da Etapa 3 (`guest-hotspot`) |
|
|
||||||
| ⑦ | `BASE_URL` | IP do ZimaOS: `http://<ip-do-zimaos>:3000`. É o endereço que o **convidado** digita/paga |
|
|
||||||
| ⑧ | `ADMIN_TOKEN` | Gere um: PowerShell: `-join ((48..57)+(65..90)+(97..122) \| Get-Random -Count 40 \| %{[char]$_})` |
|
|
||||||
|
|
||||||
### 2.3 Subir o container
|
|
||||||
|
|
||||||
No ZimaOS (interface **CasaOS**):
|
|
||||||
|
|
||||||
1. **Aplicativos → Instalar um App via Docker Compose**
|
|
||||||
2. Cole o conteúdo do `docker-compose.yml` **ou** aponte para a pasta do projeto
|
|
||||||
3. **Instalar**
|
|
||||||
|
|
||||||
Pelo terminal do ZimaOS, o equivalente é:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd HotSpot
|
|
||||||
docker compose up -d --build
|
|
||||||
```
|
|
||||||
|
|
||||||
### 2.4 Verificar
|
|
||||||
|
|
||||||
```bash
|
|
||||||
curl http://<ip-do-zimaos>:3000/api/health
|
|
||||||
# {"ok":true,"mp":true,...}
|
|
||||||
|
|
||||||
curl http://<ip-do-zimaos>:3000/api/plans
|
|
||||||
# lista os planos 1h/24h/7d
|
|
||||||
```
|
|
||||||
|
|
||||||
No navegador, abra `http://<ip-do-zimaos>:3000` — o portal INCTG deve carregar
|
|
||||||
com os 3 planos.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Etapa 3 — MikroTik (hotspot dos convidados)
|
|
||||||
|
|
||||||
### 3.1 Reset de fábrica (só se o roteador estiver bagunçado)
|
|
||||||
|
|
||||||
1. Desligue o hAP lite
|
|
||||||
2. Segure o botão **RESET** e ligue
|
|
||||||
3. Continue segurando até o LED **USR** começar a **piscar**
|
|
||||||
4. Solte — o roteador zera (login `admin`, sem senha)
|
|
||||||
|
|
||||||
### 3.2 Preparar o script
|
|
||||||
|
|
||||||
Abra `mikrotik/setup-hotspot.rsc` e ajuste o bloco inicial:
|
|
||||||
|
|
||||||
```routeros
|
|
||||||
:local backendIP "192.168.3.100" # IP do ZimaOS (igual ao BASE_URL)
|
|
||||||
:local wanInterface "ether1" # porta que vai para o modem/router da casa
|
|
||||||
:local guestInterface "ether4" # porta física para o switch dos convidados
|
|
||||||
```
|
|
||||||
|
|
||||||
Envie o arquivo ao MikroTik: **Winbox → Files → arraste o `.rsc`** para a pasta
|
|
||||||
`Files`.
|
|
||||||
|
|
||||||
### 3.3 Importar
|
|
||||||
|
|
||||||
**Winbox → New Terminal**:
|
|
||||||
|
|
||||||
```routeros
|
|
||||||
/import file-name=setup-hotspot.rsc
|
|
||||||
```
|
|
||||||
|
|
||||||
O script cria:
|
|
||||||
|
|
||||||
| O que | Detalhe |
|
|
||||||
|-------|---------|
|
|
||||||
| Bridge `bridge-guest` | Rede isolada dos convidados |
|
|
||||||
| IP `10.10.10.1/24` | Gateway da rede guest |
|
|
||||||
| AP virtual `wlan-guest` | SSID **Internet Gratis** |
|
|
||||||
| Porta `ether4` na bridge | Para switch/cabo dos convidados |
|
|
||||||
| Hotspot `guest-hotspot` | Captive portal na bridge guest |
|
|
||||||
| Pool `10.10.10.10-50` | Até 41 convidados simultâneos |
|
|
||||||
| Perfis `pix-1h/24h/7d` | Limitam velocidade (5M/8M/10M) |
|
|
||||||
| Firewall | Guest só acessa internet + backend:3000; **bloqueado** para 192.168.0.0/16, 10.x, 172.16.x |
|
|
||||||
| NAT | Convidados saem pela `ether1` |
|
|
||||||
| Walled garden | Permite fontes do portal antes do login |
|
|
||||||
|
|
||||||
### 3.4 Usuário dedicado da API (produção)
|
|
||||||
|
|
||||||
Em produção, **não use `admin`**. Crie um usuário específico no Winbox:
|
|
||||||
|
|
||||||
1. **IP → Hotspot → Users → adicionar**
|
|
||||||
2. Nome: `api-pix` · Senha: uma forte · Servidor: *(em branco = todos)*
|
|
||||||
3. **Winbox → Tools → User Manager** ou simplesmente use esse usuário nos
|
|
||||||
comandos da API via terminal para testar:
|
|
||||||
|
|
||||||
```routeros
|
|
||||||
/user add name=api-pix password=SUA-SENHA-FORTE group=full
|
|
||||||
```
|
|
||||||
|
|
||||||
Depois ajuste no compose: `MIKROTIK_USER: "api-pix"` e a senha correspondente.
|
|
||||||
|
|
||||||
### 3.5 Botão "Pagar com PIX" na tela de login do hotspot
|
|
||||||
|
|
||||||
Acesse o login do hotspot (ex.: `http://10.10.10.1/login`) e **substitua**
|
|
||||||
o arquivo `login.html` da pasta `hotspot/` do Winbox (**Files → hotspot**)
|
|
||||||
por uma página que redirecione ao portal, ou adicione um botão:
|
|
||||||
|
|
||||||
```html
|
|
||||||
<a href="http://192.168.3.100:3000/?mac=$(mac)">Pagar com PIX e liberar acesso</a>
|
|
||||||
```
|
|
||||||
|
|
||||||
> Substitua `192.168.3.100` pelo IP do ZimaOS. O parâmetro `?mac=` faz o
|
|
||||||
> backend registrar o dispositivo junto ao pagamento (auditoria).
|
|
||||||
|
|
||||||
**Alternativa sem editar HTML:** no perfil do hotspot
|
|
||||||
(**IP → Hotspot → Server Profiles → hs-guest**) use `login-by=http-chap` e
|
|
||||||
informe aos convidados o endereço `http://192.168.3.100:3000` (funciona
|
|
||||||
direto, sem redirecionamento automático).
|
|
||||||
|
|
||||||
### 3.6 Conectar o switch dos convidados
|
|
||||||
|
|
||||||
- Conecte um cabo da **ether4** do hAP para o switch/rota do convidado
|
|
||||||
- **ether1** continua sendo a WAN (modem/router principal)
|
|
||||||
- **ether2/3** não participam da rede guest (default do script)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Etapa 4 — Teste completo (sandbox)
|
|
||||||
|
|
||||||
1. Confirme `MP_ENVIRONMENT: "sandbox"` e token `TEST-` no compose
|
|
||||||
2. Reinicie: `docker compose restart` (ou CasaOS → Restart)
|
|
||||||
3. Conecte o celular no Wi-Fi **Internet Gratis**
|
|
||||||
4. Abra qualquer site → captive portal (ou digite o `BASE_URL` + `/`)
|
|
||||||
5. Escolha o plano **1 Hora** → aparece o QR Code PIX
|
|
||||||
6. Pague com a **conta sandbox** do Mercado Pago (ou use os dados de teste
|
|
||||||
do [sandbox do Pix](https://www.mercadopago.com.br/developers/pt/docs))
|
|
||||||
7. Toque em **Já paguei** (ou espere ~15s — o sistema também verifica sozinho)
|
|
||||||
8. Aparece **usuário/senha** → faça login no hotspot com esses dados
|
|
||||||
9. Confirme que a internet funciona e que **outros sites internos
|
|
||||||
(192.168.3.x) NÃO abrem** no aparelho do convidado
|
|
||||||
|
|
||||||
### 4.1 Monitorar pagamentos
|
|
||||||
|
|
||||||
```bash
|
|
||||||
curl -H "x-admin-token: SEU_ADMIN_TOKEN" http://<ip>:3000/api/admin/payments
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Etapa 5 — Checklist para produção
|
|
||||||
|
|
||||||
Siga **nesta ordem**:
|
|
||||||
|
|
||||||
- [ ] Teste da Etapa 4 passou de ponta a ponta
|
|
||||||
- [ ] Troque `MP_ACCESS_TOKEN` pelo token **produção** (`APP_USR-...`)
|
|
||||||
- [ ] Troque `MP_ENVIRONMENT` para `production`
|
|
||||||
- [ ] Crie o usuário `api-pix` no MikroTik (Etapa 3.4) e aponte o compose para ele
|
|
||||||
- [ ] Troque `ADMIN_TOKEN` por um valor longo aleatório (Etapa 2.2 ⑧)
|
|
||||||
- [ ] Reinicie o container e refaça um pagamento real baixo (R$ 3) — depois estorne no painel do MP se quiser
|
|
||||||
- [ ] Confirme que a porta 3000 do ZimaOS **não está publicada na internet** (só LAN)
|
|
||||||
- [ ] Confirme que o hAP lite **não tem portas forward** para a WAN
|
|
||||||
- [ ] Anote os planos/preços atuais e ajuste via `POST /api/admin/plans` se necessário
|
|
||||||
|
|
||||||
### Planos padrão (ajuste se quiser)
|
|
||||||
|
|
||||||
| Plano | Preço | Velocidade | Perfil MikroTik |
|
|
||||||
|-------|-------|------------|-----------------|
|
|
||||||
| 1 Hora | R$ 3,00 | 5M/1M | `pix-1h` |
|
|
||||||
| 24 Horas | R$ 5,00 | 8M/2M | `pix-24h` |
|
|
||||||
| 7 Dias | R$ 15,00 | 10M/3M | `pix-7d` |
|
|
||||||
|
|
||||||
Alterar preços/nomes: edite `backend/src/db.js` (antes do 1º run) **ou** use a
|
|
||||||
API:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
curl -X POST -H "x-admin-token: TOKEN" -H "Content-Type: application/json" \
|
|
||||||
-d '{"plans":[{"id":"plano-1h","name":"1 Hora","price":4,"profile":"pix-1h","uptime":"1h","speed":"5M/1M","active":true}]}' \
|
|
||||||
http://<ip>:3000/api/admin/plans
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Etapa 6 — CI/CD (Gitea Actions)
|
|
||||||
|
|
||||||
O repositório `jfeng/HotSpot` já tem o workflow `.gitea/workflows/docker.yml`:
|
|
||||||
|
|
||||||
1. A cada **push na `main`** (ou tag `v*`), o runner:
|
|
||||||
- Faz **checkout** do código
|
|
||||||
- **Builda** a imagem Docker do `backend/`
|
|
||||||
- Faz **push** para o Gitea Container Registry:
|
|
||||||
- `git.jf.eng.br/jfeng/hotspot:latest`
|
|
||||||
- `git.jf.eng.br/jfeng/hotspot:<sha>`
|
|
||||||
2. O login no registry usa o secret do repositório **`REGISTRY_TOKEN`**
|
|
||||||
(Settings → Secrets → Actions) — um token Gitea com escopos
|
|
||||||
`write:repository` + `write:package`
|
|
||||||
|
|
||||||
### 6.1 Instalar/atualizar no ZimaOS depois de um push
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker compose pull && docker compose up -d
|
|
||||||
```
|
|
||||||
|
|
||||||
### 6.2 Requisitos no Gitea
|
|
||||||
|
|
||||||
- [ ] **Settings → Actions → General** → Actions habilitado no repositório
|
|
||||||
- [ ] Um **runner** registrado na instância (sem runner o workflow fica
|
|
||||||
"aguardando" para sempre)
|
|
||||||
- [ ] Secret `REGISTRY_TOKEN` presente (já criado; atualize se revogar o token)
|
|
||||||
|
|
||||||
### 6.3 Fluxo de desenvolvimento
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git checkout -b feat/minha-melhoria
|
|
||||||
# ... edite ...
|
|
||||||
git add -A
|
|
||||||
git commit -m "feat: descrição objetiva"
|
|
||||||
git push -u origin feat/minha-melhoria # abre PR no Gitea
|
|
||||||
# após revisão, merge na main → CI publica nova imagem
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Identidade da marca
|
|
||||||
|
|
||||||
O portal segue o brand book da **INCTG** (`Identidade/INCTG_Brand_Book.md`):
|
|
||||||
|
|
||||||
| Elemento | Valor |
|
|
||||||
|----------|-------|
|
|
||||||
| Grafite profundo | `#101820` |
|
|
||||||
| Azul elétrico | `#246BFD` |
|
|
||||||
| Branco tecnológico | `#F4F6F8` |
|
|
||||||
| Cinza técnico | `#7C8A9A` |
|
|
||||||
| Títulos | Manrope |
|
|
||||||
| Texto/interface | Inter |
|
|
||||||
| Assinatura | *Tecnologia que resolve.* |
|
|
||||||
|
|
||||||
O logo (`Identidade/logo.png`) é servido como `backend/public/logo.png`.
|
|
||||||
Preview mobile/desktop: `Identidade/preview-mobile.png`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## API
|
## API
|
||||||
|
|
||||||
| Rota | Auth | Descrição |
|
| Rota | Acesso | Finalidade |
|
||||||
|------|------|-----------|
|
|---|---|---|
|
||||||
| `GET /api/plans` | — | Planos ativos |
|
| `GET /api/plans` | Público | Planos ativos |
|
||||||
| `POST /api/checkout` | — | Cria pagamento PIX `{planId, mac?}` |
|
| `GET /api/config` | Público | SSID, janela temporária e IP do hotspot |
|
||||||
| `GET /api/status/:id` | — | Status; entrega voucher quando `paid` |
|
| `POST /api/checkout` | Público | `{planId, mac?, payerName, payerEmail, payerCpf?, deviceId?}` |
|
||||||
| `GET /api/health` | — | Saúde + se o MP está configurado |
|
| `GET /api/status/:id` | ID aleatório da compra | Situação e voucher |
|
||||||
| `GET /api/admin/payments` | `x-admin-token` | Últimos 100 pagamentos |
|
| `POST /api/access/start` | Público, limitado | Conta temporária para um MAC presente na rede |
|
||||||
| `POST /api/admin/plans` | `x-admin-token` | Substitui a lista de planos |
|
| `POST /api/mp/webhook` | Assinatura Mercado Pago | Dispara confirmação pela API |
|
||||||
|
| `GET /api/health` | Público | Liveness |
|
||||||
|
| `GET /api/mp/public-key` | Público | Chave pública opcional do SDK |
|
||||||
|
| `POST /api/reconcile` | Admin | Consulta manual por `{orderId}` |
|
||||||
|
| `GET /api/access/status/:mac` | Admin | Diagnóstico de dispositivo |
|
||||||
|
| `GET /api/admin/users` | Admin | Lista de contas e sessões |
|
||||||
|
| `GET /api/admin/profiles` | Admin | Perfis existentes no MikroTik |
|
||||||
|
| `POST /api/admin/users` | Admin | `{name, password?, profile, uptime, comment?}` |
|
||||||
|
| `PATCH /api/admin/users/:id` | Admin | `{disabled: true/false}`, ID RouterOS |
|
||||||
|
| `GET /api/admin/users/export` | Admin | Download CSV |
|
||||||
|
| `GET /api/admin/audit` | Admin | Ações recentes |
|
||||||
|
| `GET /api/admin/payments` | Admin | Últimos 100 pagamentos |
|
||||||
|
| `POST /api/admin/plans` | Admin | Substitui planos com validação |
|
||||||
|
| `POST /api/admin/payments/:id/cancel` | Admin | Cancela pedido ainda pendente |
|
||||||
|
|
||||||
---
|
## Planos iniciais
|
||||||
|
|
||||||
## Solução de problemas
|
| Plano | Preço | Download/upload | Limite de uso |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 1 Hora | R$ 3 | 5M/1M | 1h |
|
||||||
|
| 24 Horas | R$ 5 | 8M/2M | 1d |
|
||||||
|
| 7 Dias | R$ 15 | 10M/3M | 1w |
|
||||||
|
|
||||||
| Sintoma | Causa provável | Solução |
|
Os perfis `pix-1h`, `pix-24h`, `pix-7d` precisam existir no roteador. No RouterOS, `rate-limit` usa upload/download: `1M/5M`, `2M/8M`, `3M/10M`. Alterar a informação `speed` no backend não altera o perfil no MikroTik. Compras novas salvam perfil e limite contratados para evitar que alterações futuras no plano mudem o voucher comprado.
|
||||||
|---------|----------------|---------|
|
|
||||||
| `docker compose up` falha no pull | Registry privado / sem rede | Confirme que o ZimaOS alcança `git.jf.eng.br`; o pacote é público para pull |
|
|
||||||
| Portal abre mas checkout retorna erro | Token MP inválido/sandbox trocado | Confira `MP_ACCESS_TOKEN` e `docker compose logs pix-hotspot` |
|
|
||||||
| Pagamento aprovado mas sem voucher | MikroTik inacessível | `docker compose logs` → se houver timeout de API, confira `MIKROTIK_HOST`, firewall e se o backend está na mesma rede do hAP |
|
|
||||||
| Convidado paga mas não conecta | Perfil do voucher inexistente | Os perfis `pix-1h/24h/7d` precisam existir (rode o rsc da Etapa 3) |
|
|
||||||
| Convidado acessa `192.168.3.x` | Firewall não importado | Reimporte `setup-hotspot.rsc` e teste com `ping 192.168.3.1` (deve falhar) |
|
|
||||||
| Fontes do portal não carregam | Walled garden ausente | Rode só a seção 6 do rsc (walled garden) |
|
|
||||||
| Workflow Gitea "aguardando" | Sem runner | Registre um runner na instância |
|
|
||||||
| Workflow falha no login do registry | `REGISTRY_TOKEN` revogado | Gere token novo (`write:package`) e atualize o secret |
|
|
||||||
| Push recusado: `permission denied for writing` | Deploy key sem escrita ou branch protection | Use token HTTPS ou ajuste Settings → Branches/Deploy Keys |
|
|
||||||
|
|
||||||
### Logs
|
## MikroTik
|
||||||
|
|
||||||
```bash
|
`mikrotik/setup-hotspot.rsc` é um script para **instalação nova** com o pacote wireless legado. Não é uma migração automática nem deve ser reimportado sobre a instalação atual. Ele interrompe se detectar bridge/hotspot/pool/perfil existentes ou a porta guest em outra bridge. Revise a topologia, exporte backup e use Safe Mode antes de aplicar.
|
||||||
docker compose logs -f pix-hotspot
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
O script cria rede `10.10.10.0/24`, DHCP, hotspot, perfis, NAT e guardas de firewall. Bloqueia redes privadas e acesso de gerenciamento dos convidados e mantém o processamento normal da autenticação do hotspot. A exceção de pré-login é restrita ao domínio do portal, porém CDNs podem compartilhar IPs: o walled garden por IP não garante exclusividade por domínio.
|
||||||
|
|
||||||
## Segurança — resumo
|
Copie `mikrotik/hotspot-login.html` **somente para `hotspot/login.html`**. Preserve o `alogin.html` original, que respeita o destino após o login temporário. Se a versão antiga foi copiada para ambos, restaure o `alogin.html` padrão para evitar redirecionamentos incorretos.
|
||||||
|
|
||||||
- Tokens (MP, admin, Gitea) vivem **só** no `docker-compose.yml` no servidor —
|
A API TCP 8728 deve ficar restrita ao IP LAN do backend, com usuário dedicado. A API e o login HTTP-PAP são tráfego sem TLS na LAN; para ambientes não confiáveis, configure API-SSL e hotspot HTTPS antes de adaptar os clientes. Não exponha a API RouterOS na internet.
|
||||||
nunca em commits (o `.gitignore` protege `.env`; mantenha o compose real com
|
|
||||||
credenciais apenas na máquina do ZimaOS)
|
|
||||||
- Revogue tokens que tenham sido expostos em chats/e-mails
|
|
||||||
- Rede guest isolada por firewall (não depende de SSID “escondido”)
|
|
||||||
- Portal e API não precisam de HTTPS em LAN; se um dia expuser publicamente,
|
|
||||||
coloque um proxy com TLS na frente
|
|
||||||
- Fazer backup de `backend/data/` (pagamentos e planos)
|
|
||||||
|
|
||||||
---
|
O backend não garante identidade do aparelho a partir de um MAC informado pelo cliente. O acesso temporário é vinculado ao MAC existente no roteador e tem limite/cooldown, mas prevenção completa contra spoofing exige autenticação adicional na rede. A separação entre clientes no mesmo switch exige isolamento de portas/VLAN no equipamento; firewall IP não isola tráfego de camada 2. IPv6 dos convidados deve estar bloqueado, pois o hotspot é IPv4.
|
||||||
|
|
||||||
## Estrutura do projeto
|
## Desenvolvimento e validação
|
||||||
|
|
||||||
```text
|
No diretório `backend`: `npm ci`, `npm test`, `npm audit --omit=dev`, `npm start`.
|
||||||
pix-hotspot/
|
|
||||||
├── docker-compose.yml # TUDO configurável aqui (instalação 1 clique)
|
|
||||||
├── .gitea/workflows/docker.yml # CI: build + push da imagem
|
|
||||||
├── Identidade/ # Brand book INCTG + logo
|
|
||||||
├── backend/
|
|
||||||
│ ├── Dockerfile
|
|
||||||
│ ├── package.json
|
|
||||||
│ ├── src/
|
|
||||||
│ │ ├── index.js # Express + rotas + polling de pagamentos
|
|
||||||
│ │ ├── config.js # lê as variáveis do ambiente
|
|
||||||
│ │ ├── db.js # persistência JSON (planos/pagamentos)
|
|
||||||
│ │ ├── mp.js # Mercado Pago (PIX)
|
|
||||||
│ │ └── ros.js # cliente da API RouterOS (sem dependências)
|
|
||||||
│ └── public/
|
|
||||||
│ ├── index.html # portal de pagamento INCTG
|
|
||||||
│ └── logo.png
|
|
||||||
└── mikrotik/
|
|
||||||
└── setup-hotspot.rsc # rede guest + hotspot + perfis + firewall
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
Os testes usam simulador local da API RouterOS e dados descartáveis. Cobrem autenticação, bloqueio e desconexão, criação, CSV, falhas de rede/API, webhook, referência/valor pago, confirmação concorrente e recuperação após timeout de provisionamento. Não criam pagamentos reais nem alteram roteadores reais.
|
||||||
|
|
||||||
**INCTG — Incorpore Technology Group** · *Tecnologia que resolve.*
|
Gitea Actions testa e audita antes de publicar a imagem em push na `main`/tags `v*`. O workflow usa o secret `REGISTRY_TOKEN`; a operação via MCP não depende de chaves SSH de deploy no computador.
|
||||||
|
|
||||||
|
## Limites de operação
|
||||||
|
|
||||||
|
- Execute uma única instância do backend por arquivo JSON. Alta disponibilidade e múltiplas réplicas exigem banco transacional e locks distribuídos.
|
||||||
|
- Pagamentos/vouchers contêm dados sensíveis; restrinja o volume e mantenha backups. As credenciais dos vouchers continuam armazenadas para recuperação da compra.
|
||||||
|
- Estornos posteriores à liberação não revogam automaticamente vouchers: bloqueie pelo painel quando necessário.
|
||||||
|
- Não há garantia de aprovação ou disponibilidade das APIs externas. Provisionamento de pagamento aprovado é repetido quando a conexão com o roteador retorna.
|
||||||
|
- A implantação e a configuração real do roteador precisam ser verificadas em ambiente integrado, incluindo DNS, DHCP, IPv6, isolamento, pagamento e login em celular.
|
||||||
+4
-2
@@ -1,9 +1,11 @@
|
|||||||
FROM node:20-alpine
|
FROM node:22-alpine
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY package.json package-lock.json* ./
|
COPY package.json package-lock.json* ./
|
||||||
RUN npm install --omit=dev
|
RUN npm ci --omit=dev
|
||||||
COPY src ./src
|
COPY src ./src
|
||||||
COPY public ./public
|
COPY public ./public
|
||||||
ENV NODE_ENV=production
|
ENV NODE_ENV=production
|
||||||
|
RUN mkdir -p /app/data && chown -R node:node /app
|
||||||
|
USER node
|
||||||
EXPOSE 3000
|
EXPOSE 3000
|
||||||
CMD ["node", "src/index.js"]
|
CMD ["node", "src/index.js"]
|
||||||
Generated
+7
-64
@@ -8,8 +8,8 @@
|
|||||||
"name": "pix-hotspot-backend",
|
"name": "pix-hotspot-backend",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"express": "^4.19.2",
|
"express": "4.22.3",
|
||||||
"mercadopago": "^2.13.0"
|
"mercadopago": "3.6.1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/accepts": {
|
"node_modules/accepts": {
|
||||||
@@ -461,12 +461,11 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/mercadopago": {
|
"node_modules/mercadopago": {
|
||||||
"version": "2.13.0",
|
"version": "3.6.1",
|
||||||
"resolved": "https://registry.npmjs.org/mercadopago/-/mercadopago-2.13.0.tgz",
|
"resolved": "https://registry.npmjs.org/mercadopago/-/mercadopago-3.6.1.tgz",
|
||||||
"integrity": "sha512-dm096v3Mu2VcW6j3/YJIiIAuGzzUwtGGnNga+SmfK55lpY28r1m7Zi3JyRVxSWtrwYWHT0rKs6ni05gc2kUmDw==",
|
"integrity": "sha512-JFgKCSRHMxkS1p12VMIcpI/Zki739J+5lbpl7PB0O8WHaFl4SFKQnm9paX/gqBQeh211Ozc498D49Fbe3U1jEw==",
|
||||||
"dependencies": {
|
"engines": {
|
||||||
"node-fetch": "^2.7.0",
|
"node": ">=18"
|
||||||
"uuid": "^9.0.0"
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/merge-descriptors": {
|
"node_modules/merge-descriptors": {
|
||||||
@@ -535,26 +534,6 @@
|
|||||||
"node": ">= 0.6"
|
"node": ">= 0.6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/node-fetch": {
|
|
||||||
"version": "2.7.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
|
|
||||||
"integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"whatwg-url": "^5.0.0"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": "4.x || >=6.0.0"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"encoding": "^0.1.0"
|
|
||||||
},
|
|
||||||
"peerDependenciesMeta": {
|
|
||||||
"encoding": {
|
|
||||||
"optional": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/object-inspect": {
|
"node_modules/object-inspect": {
|
||||||
"version": "1.13.4",
|
"version": "1.13.4",
|
||||||
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
|
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
|
||||||
@@ -818,12 +797,6 @@
|
|||||||
"node": ">=0.6"
|
"node": ">=0.6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/tr46": {
|
|
||||||
"version": "0.0.3",
|
|
||||||
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
|
|
||||||
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/type-is": {
|
"node_modules/type-is": {
|
||||||
"version": "1.6.18",
|
"version": "1.6.18",
|
||||||
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
|
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
|
||||||
@@ -855,20 +828,6 @@
|
|||||||
"node": ">= 0.4.0"
|
"node": ">= 0.4.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/uuid": {
|
|
||||||
"version": "9.0.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz",
|
|
||||||
"integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==",
|
|
||||||
"deprecated": "uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).",
|
|
||||||
"funding": [
|
|
||||||
"https://github.com/sponsors/broofa",
|
|
||||||
"https://github.com/sponsors/ctavan"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
|
||||||
"bin": {
|
|
||||||
"uuid": "dist/bin/uuid"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/vary": {
|
"node_modules/vary": {
|
||||||
"version": "1.1.2",
|
"version": "1.1.2",
|
||||||
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
|
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
|
||||||
@@ -877,22 +836,6 @@
|
|||||||
"engines": {
|
"engines": {
|
||||||
"node": ">= 0.8"
|
"node": ">= 0.8"
|
||||||
}
|
}
|
||||||
},
|
|
||||||
"node_modules/webidl-conversions": {
|
|
||||||
"version": "3.0.1",
|
|
||||||
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
|
|
||||||
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
|
|
||||||
"license": "BSD-2-Clause"
|
|
||||||
},
|
|
||||||
"node_modules/whatwg-url": {
|
|
||||||
"version": "5.0.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
|
|
||||||
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"tr46": "~0.0.3",
|
|
||||||
"webidl-conversions": "^3.0.0"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,10 +5,11 @@
|
|||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.js",
|
"main": "src/index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "node src/index.js"
|
"start": "node src/index.js",
|
||||||
|
"test": "node --test"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"express": "^4.19.2",
|
"express": "4.22.3",
|
||||||
"mercadopago": "^2.13.0"
|
"mercadopago": "3.6.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
:root{color-scheme:dark;--bg:#101820;--card:#17232e;--line:#2b3c4c;--text:#f4f6f8;--muted:#a4b2c0;--blue:#246bfd}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font:15px/1.5 system-ui,sans-serif}header,main,footer{max-width:1280px;margin:auto;padding:24px}header{display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line)}header strong{font-size:25px;letter-spacing:.06em}header span{color:#82aaff}header p{margin:0;color:var(--muted)}a{color:#9bbbff}h1{font-size:32px;line-height:1.2;margin:8px 0 12px}h2{font-size:20px;margin:0 0 8px}p{color:var(--muted);margin:6px 0 18px}.eyebrow{font-size:12px;font-weight:700;letter-spacing:.15em;color:#82aaff}.card{background:var(--card);border:1px solid var(--line);border-radius:16px;padding:24px;margin-bottom:20px}.login{max-width:520px;margin:8vh auto}.login label{margin:24px 0 16px}.login button{width:100%;margin-bottom:18px}small{color:var(--muted)}label{display:flex;flex-direction:column;gap:8px;font-size:13px;font-weight:600}input,select,button{font:inherit;border-radius:8px;min-height:44px;padding:10px 14px}input,select{background:#101820;color:var(--text);border:1px solid #486078;width:100%}button{background:var(--blue);color:white;font-weight:650;border:1px solid transparent;cursor:pointer}button:hover{filter:brightness(1.14)}button:disabled{opacity:.5;cursor:wait}.secondary{background:transparent;border-color:#486078}.danger{background:#652e3a;border-color:#c76a7c}.toolbar,.section-title{display:flex;justify-content:space-between;align-items:center;gap:18px}.actions{display:flex;gap:10px}.metrics{display:grid;grid-template-columns:repeat(4,1fr);gap:16px}.metrics span{display:block;color:var(--muted);font-size:13px}.metrics strong{display:block;font-size:30px;margin-top:8px}.filters{display:grid;grid-template-columns:2fr 1fr;gap:16px;margin:18px 0}.table-wrap{overflow:auto}table{border-collapse:collapse;width:100%;font-size:14px}th{text-align:left;color:var(--muted);font-size:12px;text-transform:uppercase;letter-spacing:.04em}td,th{padding:14px 12px;border-bottom:1px solid var(--line);vertical-align:top}td small{display:block}.badge{display:inline-block;padding:3px 9px;border-radius:20px;background:#2a3a4b;font-size:12px;white-space:nowrap}.badge.online{background:#174b3f;color:#9fecd3}.badge.blocked{background:#5b2934;color:#ffc2cc}.create-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:18px;align-items:end}.notice{padding:18px;margin-top:20px;border:1px solid #4488ff;border-radius:8px}pre{white-space:pre-wrap;overflow-wrap:anywhere}#message{position:fixed;bottom:18px;left:50%;transform:translateX(-50%);max-width:90vw;width:600px;background:#243b53;border:1px solid #82aaff;padding:16px 22px;border-radius:12px;color:white;box-shadow:0 8px 30px #0008;z-index:10}#message.error{background:#542634;border-color:#e992a5}footer{color:var(--muted);text-align:center;font-size:12px}button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible{outline:3px solid #a0bcff;outline-offset:3px}[hidden]{display:none!important}@media(max-width:750px){header,main,footer{padding:16px}.card{padding:18px}.metrics{grid-template-columns:repeat(2,1fr);gap:10px}.toolbar,.section-title{align-items:flex-start;flex-direction:column}.filters,.create-grid{grid-template-columns:1fr}.login{margin:30px auto}h1{font-size:27px}td,th{padding:12px 8px}}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="pt-BR">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<title>Administração • INCTG Wi-Fi</title>
|
||||||
|
<link rel="stylesheet" href="/admin.css">
|
||||||
|
<script src="/admin.js" defer></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header><div><strong>INCTG <span>Wi-Fi</span></strong><p>Administração do hotspot</p></div><a href="/">Abrir portal ↗</a></header>
|
||||||
|
<main>
|
||||||
|
<section id="login" class="card login"><p class="eyebrow">ACESSO RESTRITO</p><h1>Seu hotspot, sob controle.</h1><p>Entre com o ADMIN_TOKEN configurado no servidor.</p>
|
||||||
|
<form id="loginForm"><label>Token administrativo<input id="token" type="password" autocomplete="off" required minlength="32"></label><button>Entrar no painel</button></form><small>O token permanece apenas na memória desta aba. Ao sair ou recarregar, entre novamente.</small></section>
|
||||||
|
<div id="dashboard" hidden>
|
||||||
|
<div class="toolbar"><div><p class="eyebrow">VISÃO GERAL</p><h1>Usuários e pagamentos</h1><p id="updated">Carregando…</p></div><div class="actions"><button id="refresh" class="secondary">Atualizar</button><button id="logout" class="secondary">Sair</button></div></div>
|
||||||
|
<div class="metrics"><article class="card"><span>Usuários</span><strong id="total">—</strong></article><article class="card"><span>Online</span><strong id="online">—</strong></article><article class="card"><span>Bloqueados</span><strong id="blocked">—</strong></article><article class="card"><span>Pagamentos aprovados*</span><strong id="revenue">—</strong></article></div>
|
||||||
|
<section class="card"><div class="section-title"><div><h2>Usuários do hotspot</h2><p>Bloquear também encerra sessões e remove cookies de acesso.</p></div><button id="export" class="secondary">Exportar CSV</button></div>
|
||||||
|
<div class="filters"><label>Buscar<input id="search" type="search" placeholder="Usuário, perfil, IP ou MAC"></label><label>Situação<select id="filter"><option value="all">Todos</option><option value="online">Online</option><option value="blocked">Bloqueados</option><option value="offline">Offline</option></select></label></div>
|
||||||
|
<div class="table-wrap"><table><thead><tr><th>Usuário / perfil</th><th>Situação</th><th>Dispositivo</th><th>Tempo usado / limite</th><th>Tráfego</th><th>Ação</th></tr></thead><tbody id="users"></tbody></table></div><p id="empty" hidden>Nenhum usuário encontrado.</p></section>
|
||||||
|
<section class="card"><h2>Criar usuário</h2><p>O limite corresponde ao tempo acumulado de conexão. Deixe a senha vazia para gerar uma automaticamente.</p>
|
||||||
|
<form id="createForm" class="create-grid"><label>Usuário<input name="name" required pattern="[A-Za-z0-9_.@-]{1,64}" maxlength="64" placeholder="visitante-01"></label><label>Perfil<select id="profile" name="profile" required></select></label><label>Limite de uso<input name="uptime" required value="1h" placeholder="1h, 1d ou 1w"></label><label>Senha<input name="password" type="password" minlength="8" maxlength="128" autocomplete="new-password" placeholder="Gerar automaticamente"></label><label>Observação<input name="comment" maxlength="200"></label><button>Criar usuário</button></form>
|
||||||
|
<div id="credentials" class="notice" hidden><strong>Usuário criado. Guarde as credenciais:</strong><pre id="newCredentials"></pre><button id="hideCredentials" class="secondary">Ocultar</button></div></section>
|
||||||
|
<section class="card"><h2>Pagamentos recentes</h2><p>*Total referente aos últimos 100 registros, sem representar um fechamento contábil.</p><div class="table-wrap"><table><thead><tr><th>Data</th><th>Plano</th><th>Valor</th><th>Status</th><th>Voucher</th></tr></thead><tbody id="payments"></tbody></table></div></section>
|
||||||
|
<section class="card"><h2>Atividade administrativa</h2><div class="table-wrap"><table><thead><tr><th>Data</th><th>Ação</th><th>Usuário / quantidade</th></tr></thead><tbody id="audit"></tbody></table></div></section>
|
||||||
|
</div>
|
||||||
|
<p id="message" role="status" aria-live="polite" hidden></p>
|
||||||
|
</main><footer>INCTG · Tecnologia que resolve.</footer>
|
||||||
|
</body></html>
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
'use strict';
|
||||||
|
let token = '';
|
||||||
|
let users = [];
|
||||||
|
let noticeTimer;
|
||||||
|
const $ = id => document.getElementById(id);
|
||||||
|
function message(text, error = false) {
|
||||||
|
$('message').textContent = text; $('message').className = error ? 'error' : ''; $('message').hidden = false;
|
||||||
|
clearTimeout(noticeTimer); noticeTimer = setTimeout(() => $('message').hidden = true, 8000);
|
||||||
|
}
|
||||||
|
function logout() {
|
||||||
|
token = ''; users = []; $('token').value = ''; $('login').hidden = false; $('dashboard').hidden = true;
|
||||||
|
for (const id of ['users', 'payments', 'audit', 'newCredentials']) $(id).replaceChildren();
|
||||||
|
$('credentials').hidden = true;
|
||||||
|
}
|
||||||
|
async function api(path, options = {}) {
|
||||||
|
const res = await fetch('/api/admin' + path, { ...options, headers: { 'x-admin-token': token, ...(options.body ? { 'Content-Type': 'application/json' } : {}) }, cache: 'no-store' });
|
||||||
|
if (!res.ok) {
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
if (res.status === 401) logout();
|
||||||
|
throw new Error(data.error || 'Não foi possível concluir a operação.');
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
function cell(row, text) { const td = document.createElement('td'); td.textContent = text ?? '—'; row.append(td); return td; }
|
||||||
|
function date(value) { return value ? new Date(value).toLocaleString('pt-BR') : '—'; }
|
||||||
|
function renderUsers() {
|
||||||
|
const q = $('search').value.trim().toLowerCase(), filter = $('filter').value;
|
||||||
|
const visible = users.filter(u => JSON.stringify(u).toLowerCase().includes(q) && (filter === 'all' || filter === 'blocked' && u.disabled || filter === 'online' && u.sessions.length || filter === 'offline' && !u.sessions.length));
|
||||||
|
$('users').replaceChildren(); $('empty').hidden = visible.length > 0;
|
||||||
|
for (const u of visible) {
|
||||||
|
const row = document.createElement('tr');
|
||||||
|
const name = cell(row, u.name); const profile = document.createElement('small'); profile.textContent = u.profile; name.append(profile);
|
||||||
|
const state = cell(row, ''); const badge = document.createElement('span'); badge.className = 'badge ' + (u.disabled ? 'blocked' : u.sessions.length ? 'online' : ''); badge.textContent = u.disabled ? 'Bloqueado' : u.sessions.length ? 'Online' : 'Offline'; state.append(badge);
|
||||||
|
cell(row, u.sessions.map(s => [s.ip, s.mac].filter(Boolean).join(' · ')).join('\n') || '—');
|
||||||
|
cell(row, u.uptime + ' / ' + (u.limitUptime === '0s' ? 'Sem limite' : u.limitUptime));
|
||||||
|
cell(row, ((u.bytesIn + u.bytesOut) / 1048576).toFixed(1) + ' MB');
|
||||||
|
const action = cell(row, ''); const button = document.createElement('button'); button.className = u.disabled ? 'secondary' : 'danger'; button.textContent = u.disabled ? 'Desbloquear' : 'Bloquear';
|
||||||
|
button.onclick = async () => {
|
||||||
|
if (!u.disabled && !confirm('Bloquear ' + u.name + ' e encerrar suas sessões?')) return;
|
||||||
|
button.disabled = true;
|
||||||
|
try { await api('/users/' + encodeURIComponent(u.id), { method: 'PATCH', body: JSON.stringify({ disabled: !u.disabled }) }); await refresh(); message('Usuário atualizado.'); }
|
||||||
|
catch (e) { message(e.message + ' Atualize a lista para conferir o estado atual.', true); }
|
||||||
|
finally { button.disabled = false; }
|
||||||
|
};
|
||||||
|
action.append(button); $('users').append(row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async function refresh() {
|
||||||
|
$('refresh').disabled = true;
|
||||||
|
try {
|
||||||
|
const results = await Promise.allSettled(['/users', '/payments', '/profiles', '/audit'].map(async path => (await api(path)).json()));
|
||||||
|
if (!token) return;
|
||||||
|
const errors = results.map((r, i) => r.status === 'rejected' ? ['Usuários', 'Pagamentos', 'Perfis', 'Atividade'][i] + ': ' + r.reason.message : null).filter(Boolean);
|
||||||
|
if (results[0].status === 'fulfilled') {
|
||||||
|
users = results[0].value; renderUsers(); $('total').textContent = users.length; $('online').textContent = users.filter(u => u.sessions.length).length; $('blocked').textContent = users.filter(u => u.disabled).length;
|
||||||
|
} else { users = []; renderUsers(); for (const id of ['total','online','blocked']) $(id).textContent = '—'; }
|
||||||
|
$('payments').replaceChildren(); $('revenue').textContent = '—';
|
||||||
|
if (results[1].status === 'fulfilled') {
|
||||||
|
const payments = results[1].value;
|
||||||
|
$('revenue').textContent = payments.filter(p => p.status === 'paid').reduce((n,p) => n + p.price,0).toLocaleString('pt-BR',{style:'currency',currency:'BRL'});
|
||||||
|
for (const p of payments) { const row = document.createElement('tr'); [date(p.createdAt), p.planId, Number(p.price).toLocaleString('pt-BR',{style:'currency',currency:'BRL'}), p.status, p.voucher?.user || '—'].forEach(v => cell(row,v)); $('payments').append(row); }
|
||||||
|
}
|
||||||
|
if (results[2].status === 'fulfilled') {
|
||||||
|
const selected = $('profile').value; $('profile').replaceChildren();
|
||||||
|
for (const p of results[2].value) { const o = document.createElement('option'); o.value = p.name; o.textContent = p.name + (p.rateLimit ? ' · ' + p.rateLimit : ''); $('profile').append(o); }
|
||||||
|
if ([...$('profile').options].some(o => o.value === selected)) $('profile').value = selected;
|
||||||
|
}
|
||||||
|
$('audit').replaceChildren();
|
||||||
|
if (results[3].status === 'fulfilled') for (const a of results[3].value) { const row = document.createElement('tr'); [date(a.at),a.action,a.target].forEach(v => cell(row,v)); $('audit').append(row); }
|
||||||
|
$('updated').textContent = 'Última consulta: ' + new Date().toLocaleTimeString('pt-BR') + (errors.length ? ' · Há dados indisponíveis' : '');
|
||||||
|
if (errors.length) message(errors.join(' | '), true);
|
||||||
|
} finally { $('refresh').disabled = false; }
|
||||||
|
}
|
||||||
|
$('loginForm').onsubmit = async event => {
|
||||||
|
event.preventDefault(); token = $('token').value.trim(); const button = event.submitter; button.disabled = true;
|
||||||
|
try { await api('/audit'); $('token').value = ''; $('login').hidden = true; $('dashboard').hidden = false; await refresh(); }
|
||||||
|
catch (e) { message(e.message, true); } finally { button.disabled = false; }
|
||||||
|
};
|
||||||
|
$('logout').onclick = logout;
|
||||||
|
$('refresh').onclick = () => refresh().catch(e => message(e.message,true));
|
||||||
|
$('search').oninput = renderUsers; $('filter').onchange = renderUsers;
|
||||||
|
$('createForm').onsubmit = async event => {
|
||||||
|
event.preventDefault(); const button = event.submitter; button.disabled = true;
|
||||||
|
try {
|
||||||
|
const data = Object.fromEntries(new FormData(event.target));
|
||||||
|
const created = await (await api('/users',{method:'POST',body:JSON.stringify(data)})).json();
|
||||||
|
$('newCredentials').textContent = 'Usuário: ' + created.name + '\nSenha: ' + created.password; $('credentials').hidden = false; event.target.reset(); await refresh(); message('Usuário criado.');
|
||||||
|
} catch (e) { message(e.message,true); } finally { button.disabled = false; }
|
||||||
|
};
|
||||||
|
$('hideCredentials').onclick = () => { $('newCredentials').replaceChildren(); $('credentials').hidden = true; };
|
||||||
|
$('export').onclick = async () => {
|
||||||
|
$('export').disabled = true;
|
||||||
|
try { const blob = await (await api('/users/export')).blob(); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href=url; a.download='hotspot-usuarios.csv'; a.click(); setTimeout(()=>URL.revokeObjectURL(url),1000); message('CSV exportado sem senhas.'); }
|
||||||
|
catch(e) { message(e.message,true); } finally { $('export').disabled = false; }
|
||||||
|
};
|
||||||
@@ -602,6 +602,7 @@
|
|||||||
let toastTimer = null;
|
let toastTimer = null;
|
||||||
let selectedPlanId = null;
|
let selectedPlanId = null;
|
||||||
let mpDevice = null;
|
let mpDevice = null;
|
||||||
|
let checkoutBusy = false;
|
||||||
|
|
||||||
const $ = (id) => document.getElementById(id);
|
const $ = (id) => document.getElementById(id);
|
||||||
|
|
||||||
@@ -690,6 +691,9 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function checkout(planId) {
|
async function checkout(planId) {
|
||||||
|
if (checkoutBusy) return;
|
||||||
|
checkoutBusy = true;
|
||||||
|
$('payerNext').disabled = true;
|
||||||
try {
|
try {
|
||||||
const payerName = $('payerName').value.trim();
|
const payerName = $('payerName').value.trim();
|
||||||
const payerEmail = $('payerEmail').value.trim();
|
const payerEmail = $('payerEmail').value.trim();
|
||||||
@@ -705,6 +709,7 @@
|
|||||||
if (data.error) throw new Error(data.error);
|
if (data.error) throw new Error(data.error);
|
||||||
|
|
||||||
currentPaymentId = data.paymentId;
|
currentPaymentId = data.paymentId;
|
||||||
|
sessionStorage.setItem('paymentId', currentPaymentId);
|
||||||
$('payTitle').textContent = data.planName + ' · ' + money(data.price);
|
$('payTitle').textContent = data.planName + ' · ' + money(data.price);
|
||||||
$('qrImg').src = data.qrCodeBase64 ? 'data:image/png;base64,' + data.qrCodeBase64 : '';
|
$('qrImg').src = data.qrCodeBase64 ? 'data:image/png;base64,' + data.qrCodeBase64 : '';
|
||||||
$('copiaCola').textContent = data.copiaCola || '';
|
$('copiaCola').textContent = data.copiaCola || '';
|
||||||
@@ -715,6 +720,9 @@
|
|||||||
pollTimer = setInterval(verify, 6000);
|
pollTimer = setInterval(verify, 6000);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
toast('Erro: ' + e.message);
|
toast('Erro: ' + e.message);
|
||||||
|
} finally {
|
||||||
|
checkoutBusy = false;
|
||||||
|
$('payerNext').disabled = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -730,6 +738,7 @@
|
|||||||
btn.disabled = true;
|
btn.disabled = true;
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/status/' + encodeURIComponent(currentPaymentId));
|
const res = await fetch('/api/status/' + encodeURIComponent(currentPaymentId));
|
||||||
|
if (!res.ok) throw new Error('Falha na consulta');
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
if (data.status === 'paid' && data.voucher) {
|
if (data.status === 'paid' && data.voucher) {
|
||||||
clearInterval(pollTimer); pollTimer = null;
|
clearInterval(pollTimer); pollTimer = null;
|
||||||
@@ -763,7 +772,7 @@
|
|||||||
$('payerNext').addEventListener('click', () => checkout(selectedPlanId));
|
$('payerNext').addEventListener('click', () => checkout(selectedPlanId));
|
||||||
|
|
||||||
// ===== Login no hotspot (voucher) =====
|
// ===== Login no hotspot (voucher) =====
|
||||||
const HS_LOGIN = 'http://10.10.10.1/login';
|
let HS_LOGIN = 'http://10.10.10.1/login';
|
||||||
|
|
||||||
function hsUrl(user, pass) {
|
function hsUrl(user, pass) {
|
||||||
return HS_LOGIN + '?username=' + encodeURIComponent(user) + '&password=' + encodeURIComponent(pass);
|
return HS_LOGIN + '?username=' + encodeURIComponent(user) + '&password=' + encodeURIComponent(pass);
|
||||||
@@ -777,13 +786,22 @@
|
|||||||
const u = $('hsUser').value.trim();
|
const u = $('hsUser').value.trim();
|
||||||
const p = $('hsPass').value;
|
const p = $('hsPass').value;
|
||||||
if (!u || !p) { toast('Informe usuário e senha'); return; }
|
if (!u || !p) { toast('Informe usuário e senha'); return; }
|
||||||
window.location.href = hsUrl(u, p);
|
hotspotLogin(u, p);
|
||||||
});
|
});
|
||||||
|
|
||||||
$('hsAutoLogin').addEventListener('click', () => {
|
$('hsAutoLogin').addEventListener('click', () => {
|
||||||
window.location.href = hsUrl($('vUser').textContent, $('vPass').textContent);
|
hotspotLogin($('vUser').textContent, $('vPass').textContent);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
function hotspotLogin(user, pass, destination) {
|
||||||
|
const form = document.createElement('form');
|
||||||
|
form.method = 'POST'; form.action = HS_LOGIN;
|
||||||
|
for (const [name, value] of Object.entries({ username: user, password: pass, ...(destination ? { dst: destination } : {}) })) {
|
||||||
|
const field = document.createElement('input'); field.type = 'hidden'; field.name = name; field.value = value; form.append(field);
|
||||||
|
}
|
||||||
|
document.body.append(form); form.submit();
|
||||||
|
}
|
||||||
|
|
||||||
// ===== Internet temporaria para pagar (login automatico no hotspot) =====
|
// ===== Internet temporaria para pagar (login automatico no hotspot) =====
|
||||||
async function startFreeAccess() {
|
async function startFreeAccess() {
|
||||||
if (!mac) return;
|
if (!mac) return;
|
||||||
@@ -796,7 +814,11 @@
|
|||||||
body: JSON.stringify({ mac }),
|
body: JSON.stringify({ mac }),
|
||||||
});
|
});
|
||||||
const d = await res.json();
|
const d = await res.json();
|
||||||
if (d.loginUrl) window.location.href = d.loginUrl;
|
if (!res.ok) { sessionStorage.removeItem('freeTried'); return; }
|
||||||
|
if (d.loginUrl) {
|
||||||
|
const target = new URL(d.loginUrl);
|
||||||
|
hotspotLogin(target.searchParams.get('username'), target.searchParams.get('password'), target.searchParams.get('dst'));
|
||||||
|
}
|
||||||
} catch { /* segue */ }
|
} catch { /* segue */ }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -805,14 +827,18 @@
|
|||||||
const res = await fetch('/api/config');
|
const res = await fetch('/api/config');
|
||||||
const d = await res.json();
|
const d = await res.json();
|
||||||
if (d.ssid) $('ssidLabel').textContent = d.ssid;
|
if (d.ssid) $('ssidLabel').textContent = d.ssid;
|
||||||
|
if (/^(?:\d{1,3}\.){3}\d{1,3}$/.test(d.hotspotIp)) HS_LOGIN = 'http://' + d.hotspotIp + '/login';
|
||||||
} catch { /* usa padrao */ }
|
} catch { /* usa padrao */ }
|
||||||
}
|
}
|
||||||
|
|
||||||
if (new URLSearchParams(location.search).get('free') === '1') sessionStorage.setItem('freeOk', '1');
|
if (new URLSearchParams(location.search).get('free') === '1') sessionStorage.setItem('freeOk', '1');
|
||||||
|
|
||||||
loadSiteConfig();
|
loadSiteConfig().then(startFreeAccess);
|
||||||
loadPlans();
|
loadPlans();
|
||||||
startFreeAccess();
|
if (sessionStorage.getItem('paymentId')) {
|
||||||
|
currentPaymentId = sessionStorage.getItem('paymentId');
|
||||||
|
verify();
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import express from 'express';
|
||||||
|
import { safeAsyncRoutes } from './http.js';
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
import config from './config.js';
|
||||||
|
import { rosCommand, createHotspotUser } from './ros.js';
|
||||||
|
import { getDb, saveDb, genCode } from './db.js';
|
||||||
|
import { equalSecret, rateLimit, validName, validUptime, csvCell } from './security.js';
|
||||||
|
|
||||||
|
export function adminAuth(req, res, next) {
|
||||||
|
if (!config.adminToken || config.adminToken.length < 32 || /^(dev-token|troque|replace|changeme|cole)/i.test(config.adminToken)) {
|
||||||
|
return res.status(503).json({ error: 'Configure ADMIN_TOKEN com pelo menos 32 caracteres aleatórios.' });
|
||||||
|
}
|
||||||
|
if (!equalSecret(req.headers['x-admin-token'], config.adminToken)) return res.status(401).json({ error: 'Token inválido.' });
|
||||||
|
next();
|
||||||
|
}
|
||||||
|
|
||||||
|
const rowObject = row => Object.fromEntries(row.filter(v => v.startsWith('=')).map(v => {
|
||||||
|
const i = v.indexOf('=', 1); return [v.slice(1, i), v.slice(i + 1)];
|
||||||
|
}));
|
||||||
|
const read = async words => (await rosCommand(words)).map(rowObject);
|
||||||
|
|
||||||
|
export async function hotspotUsers() {
|
||||||
|
const [users, active] = await Promise.all([
|
||||||
|
read(['/ip/hotspot/user/print']), read(['/ip/hotspot/active/print']),
|
||||||
|
]);
|
||||||
|
return users.filter(u => u.server === config.mikrotik.server || !u.server || u.server === 'all').map(u => ({
|
||||||
|
id: u['.id'], name: u.name, profile: u.profile || 'default', disabled: u.disabled === 'true',
|
||||||
|
uptime: u.uptime || '0s', limitUptime: u['limit-uptime'] || '0s',
|
||||||
|
bytesIn: Number(u['bytes-in'] || 0), bytesOut: Number(u['bytes-out'] || 0), comment: u.comment || '',
|
||||||
|
sessions: active.filter(a => a.user === u.name && a.server === config.mikrotik.server).map(a => ({
|
||||||
|
ip: a.address, mac: a['mac-address'], uptime: a.uptime,
|
||||||
|
})),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
function audit(action, target) {
|
||||||
|
const db = getDb();
|
||||||
|
db.audit = [...(db.audit || []), { id: crypto.randomUUID(), at: new Date().toISOString(), action, target }].slice(-1000);
|
||||||
|
saveDb();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function adminRouter() {
|
||||||
|
const router = express.Router();
|
||||||
|
safeAsyncRoutes(router);
|
||||||
|
router.use(rateLimit(120, 60000), adminAuth);
|
||||||
|
router.get('/users', async (req, res) => res.json(await hotspotUsers()));
|
||||||
|
router.get('/profiles', async (req, res) => {
|
||||||
|
res.json((await read(['/ip/hotspot/user/profile/print'])).map(p => ({ name: p.name, rateLimit: p['rate-limit'] || '' })));
|
||||||
|
});
|
||||||
|
router.get('/audit', (req, res) => res.json((getDb().audit || []).slice(-100).reverse()));
|
||||||
|
router.get('/users/export', async (req, res) => {
|
||||||
|
const users = await hotspotUsers();
|
||||||
|
audit('export-users', String(users.length));
|
||||||
|
res.set('Content-Disposition', 'attachment; filename="hotspot-usuarios.csv"');
|
||||||
|
res.type('text/csv').send('\uFEFF' + [
|
||||||
|
['Usuário', 'Perfil', 'Bloqueado', 'Online', 'Tempo usado', 'Limite de uso', 'Bytes recebidos', 'Bytes enviados', 'Comentário'],
|
||||||
|
...users.map(u => [u.name, u.profile, u.disabled ? 'Sim' : 'Não', u.sessions.length ? 'Sim' : 'Não', u.uptime, u.limitUptime, u.bytesIn, u.bytesOut, u.comment]),
|
||||||
|
].map(row => row.map(csvCell).join(';')).join('\r\n'));
|
||||||
|
});
|
||||||
|
router.post('/users', async (req, res) => {
|
||||||
|
const { name, profile, uptime, comment = '' } = req.body || {};
|
||||||
|
const password = req.body?.password || genCode(12);
|
||||||
|
if (!validName(name) || !validName(profile) || !validUptime(uptime) ||
|
||||||
|
typeof password !== 'string' || password.length < 8 || password.length > 128 ||
|
||||||
|
typeof comment !== 'string' || comment.length > 200) return res.status(400).json({ error: 'Dados inválidos. Informe usuário, perfil, duração (ex.: 1h) e senha com pelo menos 8 caracteres.' });
|
||||||
|
const profiles = await read(['/ip/hotspot/user/profile/print', `?name=${profile}`]);
|
||||||
|
if (!profiles.length) return res.status(400).json({ error: 'Perfil inexistente no MikroTik.' });
|
||||||
|
const users = await read(['/ip/hotspot/user/print', `?name=${name}`]);
|
||||||
|
if (users.length) return res.status(409).json({ error: 'Usuário já existe.' });
|
||||||
|
await createHotspotUser(name, password, profile, uptime, 'pix:manual ' + comment);
|
||||||
|
audit('create-user', name);
|
||||||
|
res.status(201).json({ name, password });
|
||||||
|
});
|
||||||
|
router.patch('/users/:id', async (req, res) => {
|
||||||
|
if (!/^\*[0-9A-F]+$/i.test(req.params.id) || typeof req.body?.disabled !== 'boolean') return res.status(400).json({ error: 'Dados inválidos.' });
|
||||||
|
const user = (await hotspotUsers()).find(u => u.id === req.params.id);
|
||||||
|
if (!user) return res.status(404).json({ error: 'Usuário não encontrado neste hotspot.' });
|
||||||
|
const disabled = req.body.disabled;
|
||||||
|
await rosCommand(['/ip/hotspot/user/set', `=numbers=${user.id}`, `=disabled=${disabled ? 'yes' : 'no'}`]);
|
||||||
|
audit(disabled ? 'block-user' : 'unblock-user', user.name);
|
||||||
|
if (disabled) {
|
||||||
|
const [active, cookies] = await Promise.all([
|
||||||
|
read(['/ip/hotspot/active/print', `?user=${user.name}`]),
|
||||||
|
read(['/ip/hotspot/cookie/print', `?user=${user.name}`]),
|
||||||
|
]);
|
||||||
|
for (const a of active) await rosCommand(['/ip/hotspot/active/remove', `=numbers=${a['.id']}`]);
|
||||||
|
for (const c of cookies) await rosCommand(['/ip/hotspot/cookie/remove', `=numbers=${c['.id']}`]);
|
||||||
|
}
|
||||||
|
res.json({ ok: true });
|
||||||
|
});
|
||||||
|
return router;
|
||||||
|
}
|
||||||
+13
-1
@@ -6,6 +6,7 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|||||||
const config = {
|
const config = {
|
||||||
mpAccessToken: process.env.MP_ACCESS_TOKEN || '',
|
mpAccessToken: process.env.MP_ACCESS_TOKEN || '',
|
||||||
mpEnvironment: process.env.MP_ENVIRONMENT || 'sandbox',
|
mpEnvironment: process.env.MP_ENVIRONMENT || 'sandbox',
|
||||||
|
mpWebhookSecret: process.env.MP_WEBHOOK_SECRET || '',
|
||||||
mpPublicKey: process.env.MP_PUBLIC_KEY || '',
|
mpPublicKey: process.env.MP_PUBLIC_KEY || '',
|
||||||
mikrotik: {
|
mikrotik: {
|
||||||
host: process.env.MIKROTIK_HOST || '192.168.3.81',
|
host: process.env.MIKROTIK_HOST || '192.168.3.81',
|
||||||
@@ -20,8 +21,19 @@ const config = {
|
|||||||
ssidName: process.env.SSID_NAME || 'Internet Gratis',
|
ssidName: process.env.SSID_NAME || 'Internet Gratis',
|
||||||
hotspotIp: process.env.HOTSPOT_IP || '10.10.10.1',
|
hotspotIp: process.env.HOTSPOT_IP || '10.10.10.1',
|
||||||
baseUrl: process.env.BASE_URL || 'http://192.168.3.100:3000',
|
baseUrl: process.env.BASE_URL || 'http://192.168.3.100:3000',
|
||||||
adminToken: process.env.ADMIN_TOKEN || 'dev-token',
|
adminToken: process.env.ADMIN_TOKEN || '',
|
||||||
dataDir: process.env.DATA_DIR || path.join(__dirname, '..', 'data'),
|
dataDir: process.env.DATA_DIR || path.join(__dirname, '..', 'data'),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
for (const [name, value, max] of [
|
||||||
|
['PORT', config.port, 65535], ['MIKROTIK_PORT', config.mikrotik.port, 65535],
|
||||||
|
['FREE_ACCESS_SECONDS', config.freeAccessSeconds, 1800],
|
||||||
|
['FREE_ACCESS_COOLDOWN_SECONDS', config.freeAccessCooldownSeconds, 86400],
|
||||||
|
]) {
|
||||||
|
if (!Number.isInteger(value) || value < 1 || value > max) throw new Error(`${name} inválido`);
|
||||||
|
}
|
||||||
|
if (config.freeAccessCooldownSeconds < config.freeAccessSeconds) throw new Error('Cooldown deve ser maior ou igual ao acesso temporário');
|
||||||
|
if (!/^https?:$/.test(new URL(config.baseUrl).protocol)) throw new Error('BASE_URL inválida');
|
||||||
|
if (!/^(?:\d{1,3}\.){3}\d{1,3}$/.test(config.hotspotIp)) throw new Error('HOTSPOT_IP inválido');
|
||||||
|
|
||||||
export default config;
|
export default config;
|
||||||
+9
-2
@@ -2,6 +2,7 @@ import fs from 'node:fs';
|
|||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import crypto from 'node:crypto';
|
import crypto from 'node:crypto';
|
||||||
import config from './config.js';
|
import config from './config.js';
|
||||||
|
import { validatePlans } from './security.js';
|
||||||
|
|
||||||
const DB_PATH = path.join(config.dataDir, 'db.json');
|
const DB_PATH = path.join(config.dataDir, 'db.json');
|
||||||
|
|
||||||
@@ -17,9 +18,15 @@ export function initDb() {
|
|||||||
fs.mkdirSync(config.dataDir, { recursive: true });
|
fs.mkdirSync(config.dataDir, { recursive: true });
|
||||||
if (fs.existsSync(DB_PATH)) {
|
if (fs.existsSync(DB_PATH)) {
|
||||||
db = JSON.parse(fs.readFileSync(DB_PATH, 'utf8'));
|
db = JSON.parse(fs.readFileSync(DB_PATH, 'utf8'));
|
||||||
if (!db.plans?.length) db.plans = structuredClone(DEFAULT_PLANS);
|
if (!Array.isArray(db.plans)) db.plans = structuredClone(DEFAULT_PLANS);
|
||||||
if (!db.payments) db.payments = [];
|
if (!db.payments) db.payments = [];
|
||||||
|
if (!validatePlans(db.plans) || !Array.isArray(db.payments)) throw new Error('Banco de dados inválido; restaure um backup.');
|
||||||
if (!db.tempAccess) db.tempAccess = [];
|
if (!db.tempAccess) db.tempAccess = [];
|
||||||
|
if (!Array.isArray(db.tempAccess)) throw new Error('Acessos temporários inválidos');
|
||||||
|
// Migrate old payments to a fixed plan snapshot before plans are edited.
|
||||||
|
for (const p of db.payments) {
|
||||||
|
if (!p.uptime) p.uptime = db.plans.find(plan => plan.id === p.planId)?.uptime;
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
db = { plans: structuredClone(DEFAULT_PLANS), payments: [], tempAccess: [] };
|
db = { plans: structuredClone(DEFAULT_PLANS), payments: [], tempAccess: [] };
|
||||||
saveDb();
|
saveDb();
|
||||||
@@ -28,7 +35,7 @@ export function initDb() {
|
|||||||
|
|
||||||
export function saveDb() {
|
export function saveDb() {
|
||||||
const tmp = DB_PATH + '.tmp';
|
const tmp = DB_PATH + '.tmp';
|
||||||
fs.writeFileSync(tmp, JSON.stringify(db, null, 2));
|
fs.writeFileSync(tmp, JSON.stringify(db, null, 2), { mode: 0o600 });
|
||||||
fs.renameSync(tmp, DB_PATH);
|
fs.renameSync(tmp, DB_PATH);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
// Express 4 does not forward rejected async handlers to error middleware.
|
||||||
|
export function safeAsyncRoutes(router) {
|
||||||
|
for (const method of ['get', 'post', 'patch', 'put', 'delete']) {
|
||||||
|
const original = router[method].bind(router);
|
||||||
|
router[method] = (path, ...handlers) => {
|
||||||
|
if (!handlers.length) return original(path);
|
||||||
|
return original(path, ...handlers.map(fn => (req, res, next) => {
|
||||||
|
try { Promise.resolve(fn(req, res, next)).catch(next); } catch (e) { next(e); }
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
+86
-107
@@ -1,68 +1,62 @@
|
|||||||
import express from 'express';
|
import express from 'express';
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
import { paymentService } from './payments.js';
|
||||||
|
import { adminRouter, adminAuth } from './admin.js';
|
||||||
|
import { rateLimit, validMac, validatePlans } from './security.js';
|
||||||
|
import { safeAsyncRoutes } from './http.js';
|
||||||
|
import { verifyWebhook } from './webhook.js';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import { fileURLToPath } from 'node:url';
|
import { fileURLToPath } from 'node:url';
|
||||||
import config from './config.js';
|
import config from './config.js';
|
||||||
import { initDb, getDb, saveDb, genCode } from './db.js';
|
import { initDb, getDb, saveDb, genCode } from './db.js';
|
||||||
import { initMp, createPixPayment, getPaymentStatus, cancelOrder, validCpf } from './mp.js';
|
import { initMp, createPixPayment, getPaymentStatus, cancelOrder, validCpf } from './mp.js';
|
||||||
import { createHotspotUser, allowPaymentAccess, revokePaymentAccess, paymentAccessStatus } from './ros.js';
|
import { rosCommand, createHotspotUser, allowPaymentAccess, revokePaymentAccess, paymentAccessStatus } from './ros.js';
|
||||||
|
|
||||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||||
const app = express();
|
export const app = express();
|
||||||
app.use(express.json());
|
safeAsyncRoutes(app);
|
||||||
|
app.disable('x-powered-by');
|
||||||
|
if (process.env.TRUST_PROXY) app.set('trust proxy', process.env.TRUST_PROXY);
|
||||||
|
app.use((req, res, next) => {
|
||||||
|
res.set({ 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer', 'X-Frame-Options': 'DENY' });
|
||||||
|
if (req.path.startsWith('/api/') || req.path.startsWith('/admin')) res.set('Cache-Control', 'no-store');
|
||||||
|
if (req.path.startsWith('/admin')) res.set('Content-Security-Policy', "default-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'");
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
app.use(express.json({ limit: '16kb' }));
|
||||||
|
app.use('/api', rateLimit(300, 60000));
|
||||||
|
app.use('/api/checkout', rateLimit(10, 60000));
|
||||||
|
app.use('/api/access/start', rateLimit(10, 60000));
|
||||||
|
app.use('/api/admin', adminRouter());
|
||||||
|
app.get('/admin', (req, res) => res.sendFile(path.join(__dirname, '../public/admin.html')));
|
||||||
app.use(express.static(path.join(__dirname, '../public')));
|
app.use(express.static(path.join(__dirname, '../public')));
|
||||||
|
|
||||||
initDb();
|
initDb();
|
||||||
initMp();
|
initMp();
|
||||||
|
|
||||||
async function fulfill(payment) {
|
const { checkPayment, checks } = paymentService({ getDb, saveDb, getPaymentStatus, rosCommand, createHotspotUser });
|
||||||
if (payment.voucher) return payment;
|
|
||||||
const user = 'G' + genCode(6);
|
|
||||||
const pass = genCode(8);
|
|
||||||
const plan = getDb().plans.find((p) => p.id === payment.planId);
|
|
||||||
await createHotspotUser(user, pass, plan?.profile || payment.profile, plan?.uptime);
|
|
||||||
payment.voucher = { user, pass };
|
|
||||||
payment.status = 'paid';
|
|
||||||
payment.paidAt = new Date().toISOString();
|
|
||||||
const db = getDb();
|
|
||||||
db.tempAccess = (db.tempAccess || []).filter((t) => t.mac !== payment.mac);
|
|
||||||
if (payment.mac) revokePaymentAccess(payment.mac).catch(() => {});
|
|
||||||
saveDb();
|
|
||||||
console.log(`[PAGA] ${payment.planId} -> voucher ${user}`);
|
|
||||||
return payment;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function checkPayment(payment) {
|
|
||||||
if (!payment.mpId || payment.status !== 'pending') return payment;
|
|
||||||
try {
|
|
||||||
const st = await getPaymentStatus(payment.mpId);
|
|
||||||
if (st === 'approved') return await fulfill(payment);
|
|
||||||
if (st === 'rejected' || st === 'cancelled' || st === 'expired') {
|
|
||||||
payment.status = st;
|
|
||||||
saveDb();
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
console.error('[MP] erro ao consultar:', e.message);
|
|
||||||
}
|
|
||||||
return payment;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ===== Rotas =====
|
// ===== Rotas =====
|
||||||
|
|
||||||
// ===== Internet temporaria para pagar (bypass do hotspot) =====
|
// ===== Internet temporaria para pagar (bypass do hotspot) =====
|
||||||
|
const accessLocks = new Set();
|
||||||
app.post('/api/access/start', async (req, res) => {
|
app.post('/api/access/start', async (req, res) => {
|
||||||
const { mac } = req.body || {};
|
const mac = typeof req.body?.mac === 'string' ? req.body.mac.toUpperCase() : '';
|
||||||
if (!mac) return res.status(400).json({ error: 'mac obrigatorio' });
|
if (!validMac(mac)) return res.status(400).json({ error: 'mac obrigatorio' });
|
||||||
|
if (accessLocks.has(mac)) return res.status(409).json({ error: 'Acesso em preparação. Tente novamente.' });
|
||||||
|
accessLocks.add(mac);
|
||||||
try {
|
try {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
const prev = (db.tempAccess || []).find((t) => t.mac === mac);
|
const prev = (db.tempAccess || []).find((t) => t.mac === mac);
|
||||||
|
|
||||||
// reusa a janela criada ha menos de X minutos (evita abuso de janelas ilimitadas)
|
// reusa a janela criada ha menos de X minutos (evita abuso de janelas ilimitadas)
|
||||||
if (prev && prev.loginUrl && now - Date.parse(prev.createdAt) < config.freeAccessCooldownSeconds * 1000) {
|
if (prev && now - Date.parse(prev.createdAt) < config.freeAccessCooldownSeconds * 1000) {
|
||||||
return res.json({ ok: true, seconds: config.freeAccessSeconds, loginUrl: prev.loginUrl, reused: true });
|
if (prev.expiresAt <= now) return res.status(429).json({ error: "Aguarde para um novo acesso temporário." });
|
||||||
|
return res.json({ ok: true, seconds: Math.max(0, Math.ceil((prev.expiresAt - now) / 1000)), loginUrl: prev.loginUrl, reused: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
const minutes = Math.max(1, Math.round(config.freeAccessSeconds / 60));
|
const minutes = Math.max(1, Math.ceil(config.freeAccessSeconds / 60));
|
||||||
const r = await allowPaymentAccess(mac, minutes);
|
const r = await allowPaymentAccess(mac, minutes);
|
||||||
|
|
||||||
const back = encodeURIComponent(config.baseUrl + '/?mac=' + encodeURIComponent(mac) + '&free=1');
|
const back = encodeURIComponent(config.baseUrl + '/?mac=' + encodeURIComponent(mac) + '&free=1');
|
||||||
@@ -85,20 +79,22 @@ app.post('/api/access/start', async (req, res) => {
|
|||||||
res.json({ ok: true, seconds: config.freeAccessSeconds, loginUrl, user: r.user });
|
res.json({ ok: true, seconds: config.freeAccessSeconds, loginUrl, user: r.user });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('[ACESSO]', e.message);
|
console.error('[ACESSO]', e.message);
|
||||||
res.status(500).json({ error: e.message });
|
res.status(500).json({ error: 'Falha na operação. Consulte os logs do servidor.' });
|
||||||
|
} finally {
|
||||||
|
accessLocks.delete(mac);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
app.get('/api/access/status/:mac', async (req, res) => {
|
app.get('/api/access/status/:mac', adminAuth, async (req, res) => {
|
||||||
try {
|
try {
|
||||||
res.json(await paymentAccessStatus(req.params.mac));
|
res.json(await paymentAccessStatus(req.params.mac));
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
res.status(500).json({ error: e.message });
|
res.status(500).json({ error: 'Falha na operação. Consulte os logs do servidor.' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// ===== Reconciliacao manual (caso o webhook falhe) =====
|
// ===== Reconciliacao manual (caso o webhook falhe) =====
|
||||||
app.post('/api/reconcile', async (req, res) => {
|
app.post('/api/reconcile', adminAuth, async (req, res) => {
|
||||||
const { orderId } = req.body || {};
|
const { orderId } = req.body || {};
|
||||||
if (!orderId) return res.status(400).json({ error: 'orderId obrigatorio' });
|
if (!orderId) return res.status(400).json({ error: 'orderId obrigatorio' });
|
||||||
const payment = getDb().payments.find((p) => String(p.mpId) === String(orderId));
|
const payment = getDb().payments.find((p) => String(p.mpId) === String(orderId));
|
||||||
@@ -108,7 +104,7 @@ app.post('/api/reconcile', async (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
app.get('/api/config', (req, res) => {
|
app.get('/api/config', (req, res) => {
|
||||||
res.json({ ssid: config.ssidName, freeSeconds: config.freeAccessSeconds });
|
res.json({ ssid: config.ssidName, freeSeconds: config.freeAccessSeconds, hotspotIp: config.hotspotIp });
|
||||||
});
|
});
|
||||||
|
|
||||||
app.get('/api/plans', (req, res) => {
|
app.get('/api/plans', (req, res) => {
|
||||||
@@ -117,7 +113,10 @@ app.get('/api/plans', (req, res) => {
|
|||||||
|
|
||||||
app.post('/api/checkout', async (req, res) => {
|
app.post('/api/checkout', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { planId, mac, payerName, payerEmail, payerCpf, deviceId } = req.body || {};
|
const { planId, payerName, payerEmail, payerCpf, deviceId } = req.body || {};
|
||||||
|
const mac = typeof req.body?.mac === 'string' ? req.body.mac.toUpperCase() : '';
|
||||||
|
if (mac && !validMac(mac)) return res.status(400).json({ error: 'MAC inválido' });
|
||||||
|
if (typeof payerName !== 'string' || payerName.trim().length < 3 || payerName.length > 120 || typeof payerEmail !== 'string' || payerEmail.length > 254 || (deviceId && (typeof deviceId !== 'string' || deviceId.length > 200))) return res.status(400).json({ error: 'Dados inválidos' });
|
||||||
const plan = getDb().plans.find((p) => p.id === planId && p.active);
|
const plan = getDb().plans.find((p) => p.id === planId && p.active);
|
||||||
if (!plan) return res.status(400).json({ error: 'plano invalido' });
|
if (!plan) return res.status(400).json({ error: 'plano invalido' });
|
||||||
const email = String(payerEmail || '').trim();
|
const email = String(payerEmail || '').trim();
|
||||||
@@ -133,9 +132,10 @@ app.post('/api/checkout', async (req, res) => {
|
|||||||
const lastPurchase = hist.length ? hist[hist.length - 1].paidAt || hist[hist.length - 1].createdAt : null;
|
const lastPurchase = hist.length ? hist[hist.length - 1].paidAt || hist[hist.length - 1].createdAt : null;
|
||||||
|
|
||||||
const payment = {
|
const payment = {
|
||||||
id: 'P' + Date.now() + genCode(4),
|
id: 'P' + crypto.randomUUID(),
|
||||||
planId: plan.id,
|
planId: plan.id,
|
||||||
profile: plan.profile,
|
profile: plan.profile,
|
||||||
|
uptime: plan.uptime,
|
||||||
mac: mac || null,
|
mac: mac || null,
|
||||||
price: plan.price,
|
price: plan.price,
|
||||||
status: 'pending',
|
status: 'pending',
|
||||||
@@ -173,45 +173,18 @@ app.post('/api/checkout', async (req, res) => {
|
|||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('[CHECKOUT]', e.message);
|
console.error('[CHECKOUT]', e.message);
|
||||||
res.status(500).json({ error: e.message });
|
res.status(500).json({ error: 'Falha na operação. Consulte os logs do servidor.' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// ===== Webhook MP (IPN): confirma pagamento na hora =====
|
// ===== Webhook MP (IPN): confirma pagamento na hora =====
|
||||||
app.post('/api/mp/webhook', async (req, res) => {
|
app.post('/api/mp/webhook', async (req, res) => {
|
||||||
res.sendStatus(200); // responde rápido para o MP não reenviar
|
if (!config.mpWebhookSecret) return res.status(503).json({ error: 'Webhook não configurado; polling continua ativo.' });
|
||||||
try {
|
if (!verifyWebhook(req, config.mpWebhookSecret)) return res.sendStatus(401);
|
||||||
const d = req.body?.data || {};
|
const mpId = req.query['data.id'] || req.body?.data?.id;
|
||||||
const mpId = d.id || req.body?.id || req.query?.['data.id'] || req.query?.id;
|
const payment = getDb().payments.find(p => String(p.mpId).toLowerCase() === String(mpId).toLowerCase());
|
||||||
const extRef = d.external_reference || req.body?.external_reference || req.query?.external_reference;
|
if (payment) await checkPayment(payment);
|
||||||
const pays = d.transactions?.payments || [];
|
res.sendStatus(200);
|
||||||
const paidHint =
|
|
||||||
d.status === 'processed' ||
|
|
||||||
d.status_detail === 'accredited' ||
|
|
||||||
pays.some((p) => ['approved', 'processed'].includes(p.status));
|
|
||||||
|
|
||||||
const payment = getDb().payments.find(
|
|
||||||
(p) => (mpId && String(p.mpId) === String(mpId)) || (extRef && String(p.id) === String(extRef))
|
|
||||||
);
|
|
||||||
if (!payment) {
|
|
||||||
console.log('[WEBHOOK] nao localizado', mpId, extRef);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (paidHint && payment.status === 'pending') {
|
|
||||||
await checkPayment(payment);
|
|
||||||
if (payment.status === 'pending') {
|
|
||||||
// webhook diz pago: libera mesmo se a consulta ao MP falhar
|
|
||||||
await fulfill(payment);
|
|
||||||
saveDb();
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
await checkPayment(payment);
|
|
||||||
}
|
|
||||||
console.log(`[WEBHOOK] ${mpId || extRef} -> ${payment.status}`);
|
|
||||||
} catch (e) {
|
|
||||||
console.error('[WEBHOOK]', e.message);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
app.get('/api/status/:id', async (req, res) => {
|
app.get('/api/status/:id', async (req, res) => {
|
||||||
@@ -226,19 +199,13 @@ app.get('/api/status/:id', async (req, res) => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
function adminAuth(req, res, next) {
|
|
||||||
const token = req.headers['x-admin-token'] || req.query.token;
|
|
||||||
if (token !== config.adminToken) return res.status(401).json({ error: 'token invalido' });
|
|
||||||
next();
|
|
||||||
}
|
|
||||||
|
|
||||||
app.get('/api/admin/payments', adminAuth, (req, res) => {
|
app.get('/api/admin/payments', adminAuth, (req, res) => {
|
||||||
res.json(getDb().payments.slice(-100).reverse());
|
res.json(getDb().payments.slice(-100).reverse().map(({ qrCodeBase64, copiaCola, provisioning, ...payment }) => payment));
|
||||||
});
|
});
|
||||||
|
|
||||||
app.post('/api/admin/plans', adminAuth, (req, res) => {
|
app.post('/api/admin/plans', adminAuth, (req, res) => {
|
||||||
const { plans } = req.body || {};
|
const { plans } = req.body || {};
|
||||||
if (!Array.isArray(plans)) return res.status(400).json({ error: 'plans[] obrigatorio' });
|
if (!validatePlans(plans)) return res.status(400).json({ error: 'plans[] obrigatorio' });
|
||||||
getDb().plans = plans;
|
getDb().plans = plans;
|
||||||
saveDb();
|
saveDb();
|
||||||
res.json({ ok: true });
|
res.json({ ok: true });
|
||||||
@@ -255,13 +222,17 @@ app.post('/api/admin/payments/:id/cancel', adminAuth, async (req, res) => {
|
|||||||
return res.status(400).json({ error: 'apenas pendentes podem ser cancelados' });
|
return res.status(400).json({ error: 'apenas pendentes podem ser cancelados' });
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
await cancelOrder(payment.mpId);
|
await checkPayment(payment);
|
||||||
|
if (payment.status !== 'pending' || checks.has(payment.id)) return res.status(409).json({ error: 'Pagamento já processado.' });
|
||||||
|
const task = cancelOrder(payment.mpId);
|
||||||
|
checks.set(payment.id, task);
|
||||||
|
try { await task; } finally { checks.delete(payment.id); }
|
||||||
payment.status = 'cancelled';
|
payment.status = 'cancelled';
|
||||||
saveDb();
|
saveDb();
|
||||||
console.log(`[CANCEL] order ${payment.mpId} cancelada`);
|
console.log(`[CANCEL] order ${payment.mpId} cancelada`);
|
||||||
res.json({ ok: true, status: payment.status });
|
res.json({ ok: true, status: payment.status });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
res.status(500).json({ error: e.message });
|
res.status(500).json({ error: 'Falha na operação. Consulte os logs do servidor.' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -269,25 +240,33 @@ app.get('/api/health', async (req, res) => {
|
|||||||
res.json({ ok: true, mp: !!config.mpAccessToken && !config.mpAccessToken.includes('COLE_SEU'), time: new Date().toISOString() });
|
res.json({ ok: true, mp: !!config.mpAccessToken && !config.mpAccessToken.includes('COLE_SEU'), time: new Date().toISOString() });
|
||||||
});
|
});
|
||||||
|
|
||||||
// ===== Polling: confirma pagamentos pendentes sozinho =====
|
let polling = false;
|
||||||
setInterval(async () => {
|
setInterval(async () => {
|
||||||
const pendings = getDb().payments.filter((p) => p.status === 'pending' && p.mpId);
|
if (polling) return;
|
||||||
for (const p of pendings) await checkPayment(p);
|
polling = true;
|
||||||
}, 15000);
|
try { for (const p of getDb().payments.filter(p => p.status === 'pending' && p.mpId)) await checkPayment(p); }
|
||||||
|
finally { polling = false; }
|
||||||
// ===== Expira acessos temporarios de pagamento =====
|
}, 15000).unref();
|
||||||
|
let cleaning = false;
|
||||||
setInterval(async () => {
|
setInterval(async () => {
|
||||||
|
if (cleaning) return;
|
||||||
|
cleaning = true;
|
||||||
|
try {
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
const now = Date.now();
|
for (const t of db.tempAccess || []) {
|
||||||
const expired = (db.tempAccess || []).filter((t) => t.expiresAt <= now);
|
if (t.expiresAt <= Date.now() && !t.revoked && !accessLocks.has(t.mac)) {
|
||||||
if (!expired.length) return;
|
try { await revokePaymentAccess(t.mac); t.revoked = true; saveDb(); }
|
||||||
for (const t of expired) await revokePaymentAccess(t.mac).catch(() => {});
|
catch (e) { console.error('[ACESSO]', e.message); }
|
||||||
db.tempAccess = (db.tempAccess || []).filter((t) => t.expiresAt > now);
|
}
|
||||||
|
}
|
||||||
|
db.tempAccess = (db.tempAccess || []).filter(t => !t.revoked || Date.parse(t.createdAt) + config.freeAccessCooldownSeconds * 1000 > Date.now());
|
||||||
saveDb();
|
saveDb();
|
||||||
console.log(`[ACESSO] ${expired.length} liberacao(oes) temporaria(s) expirada(s)`);
|
} catch (e) { console.error('[LIMPEZA]', e.message); } finally { cleaning = false; }
|
||||||
}, 15000);
|
}, 15000).unref();
|
||||||
|
app.use((err, req, res, next) => {
|
||||||
app.listen(config.port, '0.0.0.0', () => {
|
console.error('[HTTP]', err.message);
|
||||||
console.log(`pix-hotspot rodando em ${config.baseUrl} (porta ${config.port})`);
|
if (res.headersSent) return next(err);
|
||||||
console.log(`MikroTik: ${config.mikrotik.host}:${config.mikrotik.port}`);
|
const status = err.type === 'entity.too.large' ? 413 : err instanceof SyntaxError && 'body' in err ? 400 : 500;
|
||||||
|
res.status(status).json({ error: status === 400 ? 'JSON inválido' : status === 413 ? 'Solicitação muito grande' : 'Falha na operação. Consulte os logs do servidor.' });
|
||||||
});
|
});
|
||||||
|
if (process.env.NODE_ENV !== 'test') app.listen(config.port, '0.0.0.0', () => console.log('pix-hotspot em ' + config.baseUrl));
|
||||||
+31
-8
@@ -125,7 +125,7 @@ export async function createPixPayment(opts) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
requestOptions: {
|
requestOptions: {
|
||||||
idempotencyKey: reference + '-' + Date.now(),
|
idempotencyKey: reference,
|
||||||
...(deviceId ? { meliSessionId: deviceId } : {}),
|
...(deviceId ? { meliSessionId: deviceId } : {}),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -152,21 +152,44 @@ export async function cancelOrder(mpId) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getPaymentStatus(mpId) {
|
export function verifyPaidOrder(data, payment) {
|
||||||
|
if (!Number.isFinite(Number(data.total_paid_amount)) || !Number.isFinite(Number(data.total_amount))) throw new Error('Valor ausente na confirmação');
|
||||||
|
if (data.external_reference !== payment.id || Math.round(Number(data.total_amount) * 100) !== Math.round(payment.price * 100) ||
|
||||||
|
Math.round(Number(data.total_paid_amount) * 100) < Math.round(payment.price * 100)) {
|
||||||
|
throw new Error('Pagamento com referência ou valor divergente');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function orderStatus(data) {
|
||||||
|
const pay = data.transactions?.payments?.[0] || {};
|
||||||
|
for (const item of [data, pay]) {
|
||||||
|
if (item.status_detail === 'expired' || item.status === 'expired') return 'expired';
|
||||||
|
if (['canceled', 'cancelled'].includes(item.status)) return 'cancelled';
|
||||||
|
if (['failed', 'rejected'].includes(item.status)) return 'rejected';
|
||||||
|
if (item.status === 'refunded') return 'refunded';
|
||||||
|
}
|
||||||
|
return data.status === 'processed' || ['approved', 'processed'].includes(pay.status) ? 'approved' : 'pending';
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getPaymentStatus(mpId, payment) {
|
||||||
// webhook pode notificar tanto a order (ORD...) quanto o pagamento (PAY...)
|
// webhook pode notificar tanto a order (ORD...) quanto o pagamento (PAY...)
|
||||||
const isOrder = String(mpId).startsWith('ORD');
|
const isOrder = String(mpId).startsWith('ORD');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (isOrder) {
|
if (isOrder) {
|
||||||
const data = await new Order(getClient()).get({ id: mpId });
|
const data = await new Order(getClient()).get({ id: mpId });
|
||||||
const pay = data.transactions?.payments?.[0] || {};
|
const status = orderStatus(data);
|
||||||
// order: action_required (waiting_transfer) = pendente | processed = pago
|
if (status === 'approved') {
|
||||||
if (data.status === 'processed' || ['approved', 'processed'].includes(pay.status)) return 'approved';
|
if (payment) verifyPaidOrder(data, payment);
|
||||||
if (['cancelled', 'rejected', 'expired', 'refunded'].includes(data.status)) return data.status;
|
return 'approved';
|
||||||
if (['cancelled', 'rejected', 'refunded'].includes(pay.status)) return pay.status;
|
}
|
||||||
return 'pending';
|
return status;
|
||||||
}
|
}
|
||||||
const data = await new Payment(getClient()).get({ id: mpId });
|
const data = await new Payment(getClient()).get({ id: mpId });
|
||||||
|
if (data.status === 'approved' && payment) {
|
||||||
|
verifyPaidOrder({ external_reference: data.external_reference, total_amount: data.transaction_amount, total_paid_amount: data.transaction_amount }, payment);
|
||||||
|
if (data.currency_id !== 'BRL') throw new Error('Moeda inesperada');
|
||||||
|
}
|
||||||
// payment: pending | approved | rejected | cancelled | expired ...
|
// payment: pending | approved | rejected | cancelled | expired ...
|
||||||
return data.status;
|
return data.status;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { genCode } from './db.js';
|
||||||
|
|
||||||
|
// One application process owns the JSON database and these per-payment locks.
|
||||||
|
export function paymentService({ getDb, saveDb, getPaymentStatus, rosCommand, createHotspotUser }) {
|
||||||
|
const checks = new Map();
|
||||||
|
async function fulfill(payment) {
|
||||||
|
if (payment.voucher) return payment;
|
||||||
|
if (!payment.uptime) throw new Error('Pagamento sem limite de uso');
|
||||||
|
if (!payment.provisioning) {
|
||||||
|
payment.provisioning = { user: 'G' + genCode(12), pass: genCode(16) };
|
||||||
|
saveDb();
|
||||||
|
}
|
||||||
|
const { user, pass } = payment.provisioning;
|
||||||
|
const marker = 'pix:' + payment.id;
|
||||||
|
const rows = await rosCommand(['/ip/hotspot/user/print', '?name=' + user]);
|
||||||
|
if (rows.length) {
|
||||||
|
if (!rows.some(row => row.includes('=comment=' + marker))) throw new Error('Conflito no voucher');
|
||||||
|
} else await createHotspotUser(user, pass, payment.profile, payment.uptime, marker);
|
||||||
|
payment.voucher = { user, pass };
|
||||||
|
payment.status = 'paid';
|
||||||
|
payment.paidAt = new Date().toISOString();
|
||||||
|
delete payment.provisioning;
|
||||||
|
if (payment.mac) {
|
||||||
|
const temp = (getDb().tempAccess || []).find(t => t.mac === payment.mac);
|
||||||
|
if (temp) temp.expiresAt = Date.now();
|
||||||
|
}
|
||||||
|
saveDb();
|
||||||
|
return payment;
|
||||||
|
}
|
||||||
|
async function checkPayment(payment) {
|
||||||
|
if (!payment.mpId || payment.status !== 'pending') return payment;
|
||||||
|
if (checks.has(payment.id)) return checks.get(payment.id);
|
||||||
|
const task = (async () => {
|
||||||
|
try {
|
||||||
|
const st = await getPaymentStatus(payment.mpId, payment);
|
||||||
|
if (st === 'approved') return await fulfill(payment);
|
||||||
|
if (['rejected', 'cancelled', 'expired', 'refunded'].includes(st)) { payment.status = st; saveDb(); }
|
||||||
|
} catch (e) { console.error('[PAGAMENTO]', e.message); }
|
||||||
|
return payment;
|
||||||
|
})();
|
||||||
|
checks.set(payment.id, task);
|
||||||
|
try { return await task; } finally { checks.delete(payment.id); }
|
||||||
|
}
|
||||||
|
return { checkPayment, checks };
|
||||||
|
}
|
||||||
+22
-24
@@ -1,5 +1,6 @@
|
|||||||
import net from 'node:net';
|
import net from 'node:net';
|
||||||
import config from './config.js';
|
import config from './config.js';
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
|
||||||
function packLen(n) {
|
function packLen(n) {
|
||||||
if (n < 0x80) return Buffer.from([n]);
|
if (n < 0x80) return Buffer.from([n]);
|
||||||
@@ -30,6 +31,7 @@ class Parser {
|
|||||||
}
|
}
|
||||||
push(chunk) {
|
push(chunk) {
|
||||||
this.buf = Buffer.concat([this.buf, chunk]);
|
this.buf = Buffer.concat([this.buf, chunk]);
|
||||||
|
if (this.buf.length > 8 * 1024 * 1024) { this.error = 'Resposta RouterOS excede o limite'; return; }
|
||||||
while (true) {
|
while (true) {
|
||||||
if (this.buf.length === 0) return;
|
if (this.buf.length === 0) return;
|
||||||
const first = this.buf[0];
|
const first = this.buf[0];
|
||||||
@@ -44,10 +46,11 @@ class Parser {
|
|||||||
} else if ((first & 0xf0) === 0xe0) {
|
} else if ((first & 0xf0) === 0xe0) {
|
||||||
if (this.buf.length < 4) return;
|
if (this.buf.length < 4) return;
|
||||||
len = ((first & 0x0f) << 24) | (this.buf[1] << 16) | (this.buf[2] << 8) | this.buf[3]; offset = 4;
|
len = ((first & 0x0f) << 24) | (this.buf[1] << 16) | (this.buf[2] << 8) | this.buf[3]; offset = 4;
|
||||||
} else {
|
} else if (first === 0xf0) {
|
||||||
if (this.buf.length < 5) return;
|
if (this.buf.length < 5) return;
|
||||||
len = (this.buf[1] << 24) | (this.buf[2] << 16) | (this.buf[3] << 8) | this.buf[4]; offset = 5;
|
len = (this.buf[1] << 24) | (this.buf[2] << 16) | (this.buf[3] << 8) | this.buf[4]; offset = 5;
|
||||||
}
|
} else { this.error = 'Comprimento RouterOS inválido'; return; }
|
||||||
|
if (len < 0 || len > 8 * 1024 * 1024) { this.error = 'Resposta RouterOS inválida'; return; }
|
||||||
if (this.buf.length < offset + len) return;
|
if (this.buf.length < offset + len) return;
|
||||||
const data = this.buf.subarray(offset, offset + len);
|
const data = this.buf.subarray(offset, offset + len);
|
||||||
this.buf = this.buf.subarray(offset + len);
|
this.buf = this.buf.subarray(offset + len);
|
||||||
@@ -70,11 +73,12 @@ class Parser {
|
|||||||
if (attr === '!re') this.replies.push(words.slice(1));
|
if (attr === '!re') this.replies.push(words.slice(1));
|
||||||
else if (attr === '!done') this.done = true;
|
else if (attr === '!done') this.done = true;
|
||||||
else if (attr === '!trap') this.error = words.slice(1).join(' ') || 'trap';
|
else if (attr === '!trap') this.error = words.slice(1).join(' ') || 'trap';
|
||||||
|
else if (attr === '!fatal') this.error = 'RouterOS encerrou a conexão';
|
||||||
else this.replies.push(words);
|
else this.replies.push(words);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function rosCommand(words, timeoutMs = 8000) {
|
export async function rosCommand(words, timeoutMs = 8000) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const socket = new net.Socket();
|
const socket = new net.Socket();
|
||||||
const parser = new Parser();
|
const parser = new Parser();
|
||||||
@@ -116,13 +120,14 @@ async function rosCommand(words, timeoutMs = 8000) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createHotspotUser(name, password, profile, uptime) {
|
export async function createHotspotUser(name, password, profile, uptime, comment = 'pix:manual') {
|
||||||
const words = [
|
const words = [
|
||||||
'/ip/hotspot/user/add',
|
'/ip/hotspot/user/add',
|
||||||
`=server=${config.mikrotik.server}`,
|
`=server=${config.mikrotik.server}`,
|
||||||
`=name=${name}`,
|
`=name=${name}`,
|
||||||
`=password=${password}`,
|
`=password=${password}`,
|
||||||
`=profile=${profile}`,
|
`=profile=${profile}`,
|
||||||
|
`=comment=${comment}`,
|
||||||
];
|
];
|
||||||
if (uptime) words.push(`=limit-uptime=${uptime}`);
|
if (uptime) words.push(`=limit-uptime=${uptime}`);
|
||||||
await rosCommand(words);
|
await rosCommand(words);
|
||||||
@@ -154,17 +159,15 @@ async function hostAddressByMac(mac) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function freeUserName(mac) {
|
function freeUserName(mac) {
|
||||||
return 'FREE' + String(mac || '').replace(/[^0-9A-Fa-f]/g, '').slice(-10).toUpperCase();
|
return 'FREE' + String(mac || '').replace(/[^0-9A-Fa-f]/g, '').toUpperCase();
|
||||||
}
|
}
|
||||||
|
|
||||||
async function removeUserByName(name) {
|
async function removeUserByName(name) {
|
||||||
try {
|
|
||||||
const rows = await rosCommand(['/ip/hotspot/user/print', `?name=${name}`]);
|
const rows = await rosCommand(['/ip/hotspot/user/print', `?name=${name}`]);
|
||||||
for (const row of rows || []) {
|
for (const row of rows || []) {
|
||||||
const id = pickField(row, '=.id=');
|
const id = pickField(row, '=.id=');
|
||||||
if (id) await rosCommand(['/ip/hotspot/user/remove', `=numbers=${id}`]);
|
if (id) await rosCommand(['/ip/hotspot/user/remove', `=numbers=${id}`]);
|
||||||
}
|
}
|
||||||
} catch { /* ignora */ }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function ensureFreeProfile(rateLimit = '3M/3M') {
|
async function ensureFreeProfile(rateLimit = '3M/3M') {
|
||||||
@@ -181,7 +184,7 @@ async function ensureFreeProfile(rateLimit = '3M/3M') {
|
|||||||
const id = pickField((again || [])[0], '=.id=');
|
const id = pickField((again || [])[0], '=.id=');
|
||||||
if (id) await rosCommand(['/ip/hotspot/user/profile/set', `=numbers=${id}`, `=rate-limit=${rateLimit}`]);
|
if (id) await rosCommand(['/ip/hotspot/user/profile/set', `=numbers=${id}`, `=rate-limit=${rateLimit}`]);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('[PERFIL pix-free]', e.message);
|
throw new Error('Não foi possível preparar o perfil temporário', { cause: e });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -198,9 +201,12 @@ async function removeActiveByMac(mac) {
|
|||||||
// Cria um usuario temporario do hotspot (o portal faz login automatico nele)
|
// Cria um usuario temporario do hotspot (o portal faz login automatico nele)
|
||||||
export async function allowPaymentAccess(mac, minutes = 10) {
|
export async function allowPaymentAccess(mac, minutes = 10) {
|
||||||
if (!mac) throw new Error('mac obrigatorio');
|
if (!mac) throw new Error('mac obrigatorio');
|
||||||
|
if (!await hostAddressByMac(mac)) throw new Error('Dispositivo não encontrado na rede do hotspot');
|
||||||
|
const sessions = await rosCommand(['/ip/hotspot/active/print', `?mac-address=${mac}`]);
|
||||||
|
if (sessions.some(row => pickField(row, '=user=') !== freeUserName(mac))) throw new Error('Dispositivo já possui uma sessão autenticada');
|
||||||
await ensureFreeProfile();
|
await ensureFreeProfile();
|
||||||
const name = freeUserName(mac);
|
const name = freeUserName(mac);
|
||||||
const pass = 'F' + Math.random().toString(36).slice(2, 9).toUpperCase();
|
const pass = crypto.randomBytes(16).toString('hex');
|
||||||
await removeUserByName(name);
|
await removeUserByName(name);
|
||||||
await rosCommand([
|
await rosCommand([
|
||||||
'/ip/hotspot/user/add',
|
'/ip/hotspot/user/add',
|
||||||
@@ -208,6 +214,7 @@ export async function allowPaymentAccess(mac, minutes = 10) {
|
|||||||
`=name=${name}`,
|
`=name=${name}`,
|
||||||
`=password=${pass}`,
|
`=password=${pass}`,
|
||||||
'=profile=pix-free',
|
'=profile=pix-free',
|
||||||
|
`=mac-address=${mac}`,
|
||||||
`=limit-uptime=${minutes}m`,
|
`=limit-uptime=${minutes}m`,
|
||||||
]);
|
]);
|
||||||
return { user: name, pass, mac };
|
return { user: name, pass, mac };
|
||||||
@@ -234,22 +241,13 @@ export async function paymentAccessStatus(mac) {
|
|||||||
|
|
||||||
export async function revokePaymentAccess(mac) {
|
export async function revokePaymentAccess(mac) {
|
||||||
if (!mac) return;
|
if (!mac) return;
|
||||||
await removeActiveByMac(mac);
|
// Disconnect only the temporary account, never the paid voucher for this MAC.
|
||||||
|
const active = await rosCommand(['/ip/hotspot/active/print', `?user=${freeUserName(mac)}`]);
|
||||||
|
for (const row of active) {
|
||||||
|
const id = pickField(row, '=.id=');
|
||||||
|
if (id) await rosCommand(['/ip/hotspot/active/remove', `=numbers=${id}`]);
|
||||||
|
}
|
||||||
await removeUserByName(freeUserName(mac));
|
await removeUserByName(freeUserName(mac));
|
||||||
try {
|
|
||||||
const bindings = await rosCommand(['/ip/hotspot/ip-binding/print', `?mac-address=${mac}`]);
|
|
||||||
for (const row of bindings || []) {
|
|
||||||
const id = row.find((w) => w.startsWith('=.id='));
|
|
||||||
if (id) await rosCommand(['/ip/hotspot/ip-binding/remove', `=numbers=${id.slice(5)}`]);
|
|
||||||
}
|
|
||||||
} catch { /* ignora */ }
|
|
||||||
try {
|
|
||||||
const queues = await rosCommand(['/queue/simple/print', `?name=pixpagando-${mac}`]);
|
|
||||||
for (const row of queues || []) {
|
|
||||||
const id = row.find((w) => w.startsWith('=.id='));
|
|
||||||
if (id) await rosCommand(['/queue/simple/remove', `=numbers=${id.slice(5)}`]);
|
|
||||||
}
|
|
||||||
} catch { /* ignora */ }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function mikrotikPing() {
|
export async function mikrotikPing() {
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import crypto from 'node:crypto';
|
||||||
|
|
||||||
|
export function equalSecret(a, b) {
|
||||||
|
if (typeof a !== 'string' || typeof b !== 'string') return false;
|
||||||
|
const x = crypto.createHash('sha256').update(a).digest();
|
||||||
|
const y = crypto.createHash('sha256').update(b).digest();
|
||||||
|
return crypto.timingSafeEqual(x, y);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const validMac = (mac) => typeof mac === 'string' && /^([0-9a-f]{2}:){5}[0-9a-f]{2}$/i.test(mac);
|
||||||
|
export const validUptime = (v) => typeof v === 'string' && v.length <= 40 && /^(?:\d+[wdhms])+$/.test(v) && /[1-9]/.test(v);
|
||||||
|
export const validName = (v) => typeof v === 'string' && /^[A-Za-z0-9_.@-]{1,64}$/.test(v);
|
||||||
|
|
||||||
|
export function validatePlans(plans) {
|
||||||
|
if (!Array.isArray(plans) || plans.length > 50) return false;
|
||||||
|
const ids = new Set();
|
||||||
|
return plans.every(p => {
|
||||||
|
if (!p || !validName(p.id) || ids.has(p.id) || !validName(p.profile) ||
|
||||||
|
typeof p.name !== 'string' || !p.name.trim() || p.name.length > 100 ||
|
||||||
|
typeof p.price !== 'number' || !Number.isFinite(p.price) || p.price < 0.01 || p.price > 10000 ||
|
||||||
|
Math.abs(p.price * 100 - Math.round(p.price * 100)) > 0.00001 ||
|
||||||
|
!validUptime(p.uptime) || typeof p.speed !== 'string' || p.speed.length > 40 || typeof p.active !== 'boolean') return false;
|
||||||
|
ids.add(p.id);
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function rateLimit(limit, windowMs) {
|
||||||
|
const buckets = new Map();
|
||||||
|
return (req, res, next) => {
|
||||||
|
const now = Date.now();
|
||||||
|
for (const [key, value] of buckets) if (value.until <= now) buckets.delete(key);
|
||||||
|
const key = req.ip;
|
||||||
|
const bucket = buckets.get(key) || { count: 0, until: now + windowMs };
|
||||||
|
buckets.set(key, bucket);
|
||||||
|
if (++bucket.count > limit) {
|
||||||
|
res.set('Retry-After', String(Math.ceil((bucket.until - now) / 1000)));
|
||||||
|
return res.status(429).json({ error: 'Muitas solicitações. Tente novamente em instantes.' });
|
||||||
|
}
|
||||||
|
next();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function csvCell(value) {
|
||||||
|
let text = String(value ?? '');
|
||||||
|
if (/^[\s]*[=+@-]/.test(text)) text = "'" + text;
|
||||||
|
return '"' + text.replaceAll('"', '""') + '"';
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import crypto from 'node:crypto';
|
||||||
|
import { equalSecret } from './security.js';
|
||||||
|
|
||||||
|
export function verifyWebhook(req, secret) {
|
||||||
|
const parts = Object.fromEntries(String(req.headers['x-signature'] || '').split(',').map(p => p.trim().split('=')));
|
||||||
|
const id = req.query['data.id'] || req.body?.data?.id;
|
||||||
|
const requestId = req.headers['x-request-id'];
|
||||||
|
if (!secret || typeof id !== 'string' || typeof requestId !== 'string' || !/^\d+$/.test(parts.ts || '') || !/^[a-f0-9]{64}$/i.test(parts.v1 || '')) return false;
|
||||||
|
const timestamp = Number(parts.ts) * (parts.ts.length <= 10 ? 1000 : 1);
|
||||||
|
if (Math.abs(Date.now() - timestamp) > 5 * 60 * 1000) return false;
|
||||||
|
const manifest = `id:${id.toLowerCase()};request-id:${requestId};ts:${parts.ts};`;
|
||||||
|
const signature = crypto.createHmac('sha256', secret).update(manifest).digest('hex');
|
||||||
|
return equalSecret(signature, parts.v1.toLowerCase());
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import net from 'node:net';
|
||||||
|
|
||||||
|
test('admin API authenticates, creates, lists, blocks, disconnects and exports with a local RouterOS simulator', async t => {
|
||||||
|
const users=[{'.id':'*1',name:'existing',profile:'pix-1h',server:'guest-hotspot',disabled:'false',uptime:'1m','limit-uptime':'1h',comment:'=FORMULA()'}];
|
||||||
|
const active=[{'.id':'*A',user:'existing',server:'guest-hotspot',address:'10.10.10.10','mac-address':'AA:BB:CC:DD:EE:FF'}];
|
||||||
|
const cookies=[{'.id':'*B',user:'existing'}];
|
||||||
|
let trap=false;
|
||||||
|
function encode(words) {
|
||||||
|
return Buffer.concat([...words.flatMap(w=>{const b=Buffer.from(w);return [b.length<128?Buffer.from([b.length]):Buffer.from([0x80 | b.length>>8,b.length&255]),b];}),Buffer.from([0])]);
|
||||||
|
}
|
||||||
|
const ros=net.createServer(socket=>{
|
||||||
|
let buf=Buffer.alloc(0),words=[];
|
||||||
|
socket.on('data',chunk=>{
|
||||||
|
buf=Buffer.concat([buf,chunk]);
|
||||||
|
while(buf.length){
|
||||||
|
let n=buf[0],off=1;if(n&128){if(buf.length<2)return;n=((n&63)<<8)|buf[1];off=2;}
|
||||||
|
if(buf.length<off+n)return;
|
||||||
|
if(n){words.push(buf.subarray(off,off+n).toString());buf=buf.subarray(off+n);continue;}
|
||||||
|
buf=buf.subarray(off);const cmd=words;words=[];
|
||||||
|
const args=Object.fromEntries(cmd.slice(1).filter(w=>w[0]==='=').map(w=>{const i=w.indexOf('=',1);return[w.slice(1,i),w.slice(i+1)];}));
|
||||||
|
if(cmd[0]==='/login'){socket.write(encode(['!done']));continue;}
|
||||||
|
if(trap){socket.write(encode(['!trap','=message=simulated failure']));continue;}
|
||||||
|
let rows=[];
|
||||||
|
if(cmd[0]==='/ip/hotspot/user/print') rows=users;
|
||||||
|
if(cmd[0]==='/ip/hotspot/active/print') rows=active;
|
||||||
|
if(cmd[0]==='/ip/hotspot/cookie/print') rows=cookies;
|
||||||
|
if(cmd[0]==='/ip/hotspot/user/profile/print') rows=[{name:'pix-1h','rate-limit':'5M/1M'}];
|
||||||
|
for(const query of cmd.filter(w=>w[0]==='?')){const i=query.indexOf('=');rows=rows.filter(r=>r[query.slice(1,i)]===query.slice(i+1));}
|
||||||
|
if(cmd[0]==='/ip/hotspot/user/add') users.push({'.id':'*2',...args,disabled:'false'});
|
||||||
|
if(cmd[0]==='/ip/hotspot/user/set') Object.assign(users.find(u=>u['.id']===args.numbers),{disabled:args.disabled==='yes'?'true':'false'});
|
||||||
|
if(cmd[0]==='/ip/hotspot/active/remove') active.splice(active.findIndex(a=>a['.id']===args.numbers),1);
|
||||||
|
if(cmd[0]==='/ip/hotspot/cookie/remove') cookies.splice(cookies.findIndex(a=>a['.id']===args.numbers),1);
|
||||||
|
for(const row of rows) socket.write(encode(['!re',...Object.entries(row).map(([k,v])=>'='+k+'='+v)]));
|
||||||
|
socket.write(encode(['!done']));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
await new Promise(r=>ros.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>ros.close(r)));
|
||||||
|
process.env.NODE_ENV='test';process.env.MIKROTIK_HOST='127.0.0.1';process.env.MIKROTIK_PORT=String(ros.address().port);process.env.ADMIN_TOKEN='a'.repeat(48);
|
||||||
|
const dataDir=fs.mkdtempSync(path.join(os.tmpdir(),'hotspot-test-'));process.env.DATA_DIR=dataDir;
|
||||||
|
t.after(()=>fs.rmSync(dataDir,{recursive:true,force:true}));
|
||||||
|
const { app }=await import('../src/index.js');
|
||||||
|
const server=app.listen(0,'127.0.0.1');await new Promise(r=>server.once('listening',r));t.after(()=>new Promise(r=>server.close(r)));
|
||||||
|
const base='http://127.0.0.1:'+server.address().port;
|
||||||
|
const request=(url,method='GET',body)=>fetch(base+url,{method,headers:{'x-admin-token':process.env.ADMIN_TOKEN,'Content-Type':'application/json'},body:body===undefined?undefined:JSON.stringify(body)});
|
||||||
|
assert.equal((await fetch(base+'/api/admin/users')).status,401);
|
||||||
|
const { default: config } = await import('../src/config.js');
|
||||||
|
const originalToken = config.adminToken;
|
||||||
|
config.adminToken = 'replace-with-at-least-32-random-characters';
|
||||||
|
assert.equal((await request('/api/admin/users')).status,503);
|
||||||
|
config.adminToken = originalToken;
|
||||||
|
assert.equal((await fetch(base+'/api/admin/users?token='+process.env.ADMIN_TOKEN)).status,401);
|
||||||
|
let res=await request('/api/admin/users');assert.equal(res.status,200);let list=await res.json();assert.equal(list[0].sessions.length,1);assert.equal('password' in list[0],false);
|
||||||
|
res=await request('/api/admin/users','POST',{name:'new-user',profile:'pix-1h',uptime:'1h'});assert.equal(res.status,201);assert.ok((await res.json()).password.length>=8);
|
||||||
|
assert.equal((await request('/api/admin/users','POST',{name:'new-user',profile:'pix-1h',uptime:'1h'})).status,409);
|
||||||
|
assert.equal((await request('/api/admin/users/*1','PATCH',{disabled:true})).status,200);assert.equal(users[0].disabled,'true');assert.equal(active.length,0);assert.equal(cookies.length,0);
|
||||||
|
assert.equal((await request('/api/admin/users/*1','PATCH',{disabled:false})).status,200);assert.equal(users[0].disabled,'false');
|
||||||
|
res=await request('/api/admin/users/export');assert.equal(res.status,200);const csv=await res.text();assert.ok(csv.includes("'=FORMULA()"));assert.ok(!csv.includes('password'));
|
||||||
|
assert.equal((await request('/api/admin/users/*F','PATCH',{disabled:true})).status,404);
|
||||||
|
assert.equal((await request('/api/admin/plans','POST',{plans:[{price:-1}]})).status,400);
|
||||||
|
assert.equal((await request('/api/mp/webhook','POST',{data:{id:'ORD1',status:'processed'}})).status,503);
|
||||||
|
assert.equal((await fetch(base+'/api/admin/plans',{method:'POST',headers:{'Content-Type':'application/json'},body:'{'})).status,400);
|
||||||
|
trap=true;res=await request('/api/admin/users');assert.equal(res.status,500);assert.ok(!(await res.text()).includes('simulated failure'));
|
||||||
|
const html=await fetch(base+'/admin');assert.equal(html.status,200);assert.ok((await html.text()).includes('Criar usuário'));
|
||||||
|
});
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
import { validMac, validatePlans, csvCell } from '../src/security.js';
|
||||||
|
import { verifyWebhook } from '../src/webhook.js';
|
||||||
|
import { verifyPaidOrder, orderStatus } from '../src/mp.js';
|
||||||
|
import { paymentService } from '../src/payments.js';
|
||||||
|
|
||||||
|
test('webhook accepts signed notifications and rejects forged, expired and modified IDs', () => {
|
||||||
|
const ts = String(Date.now()), secret = 'secret', id = 'ORD123';
|
||||||
|
const v1 = crypto.createHmac('sha256', secret).update(`id:${id.toLowerCase()};request-id:req1;ts:${ts};`).digest('hex');
|
||||||
|
const req = { query: { 'data.id': id }, headers: { 'x-request-id': 'req1', 'x-signature': `ts=${ts},v1=${v1}` } };
|
||||||
|
assert.equal(verifyWebhook(req, secret), true);
|
||||||
|
assert.equal(verifyWebhook(req, 'wrong'), false);
|
||||||
|
req.query['data.id'] = 'ORD456'; assert.equal(verifyWebhook(req, secret), false);
|
||||||
|
req.query['data.id'] = id; req.headers['x-signature'] = `ts=1,v1=${v1}`;
|
||||||
|
assert.equal(verifyWebhook(req, secret), false);
|
||||||
|
});
|
||||||
|
test('only the expected reference and fully paid amount are accepted', () => {
|
||||||
|
const payment = { id: 'P1', price: 3 };
|
||||||
|
const data = { external_reference: 'P1', total_amount: '3.00', total_paid_amount: '3.00' };
|
||||||
|
assert.doesNotThrow(() => verifyPaidOrder(data, payment));
|
||||||
|
for (const patch of [{ external_reference: 'P2' }, { total_amount: '0.01' }, { total_paid_amount: '0.01' }, { total_paid_amount: undefined }, { total_paid_amount: 'NaN' }]) assert.throws(() => verifyPaidOrder({ ...data, ...patch }, payment));
|
||||||
|
});
|
||||||
|
test('validates plan changes and neutralizes CSV formulas', () => {
|
||||||
|
const p = { id:'p1',name:'Hora',price:3,profile:'pix-1h',uptime:'1h',speed:'5M/1M',active:true };
|
||||||
|
assert.equal(validatePlans([p]),true);
|
||||||
|
for (const patch of [{price:-1},{price:'3'},{price:NaN},{price:3.001},{uptime:'0h'},{profile:'bad\nvalue'}]) assert.equal(validatePlans([{...p,...patch}]),false);
|
||||||
|
assert.equal(validatePlans([p,p]),false);
|
||||||
|
assert.equal(validMac('AA:BB:CC:DD:EE:FF'),true); assert.equal(validMac('anything'),false);
|
||||||
|
assert.equal(csvCell('=HYPERLINK("bad")'),'"\'=HYPERLINK(""bad"")"');
|
||||||
|
});
|
||||||
|
test('normalizes Orders API cancellations, failures, expirations and refunds', () => {
|
||||||
|
for (const [status, expected] of [['canceled','cancelled'],['failed','rejected'],['refunded','refunded'],['processed','approved'],['action_required','pending']]) assert.equal(orderStatus({status}),expected);
|
||||||
|
assert.equal(orderStatus({status:'canceled',status_detail:'expired'}),'expired');
|
||||||
|
assert.equal(orderStatus({status:'processed',transactions:{payments:[{status:'refunded'}]}}),'refunded');
|
||||||
|
});
|
||||||
|
test('simultaneous confirmations issue only one voucher', async () => {
|
||||||
|
let creates=0, queries=0;
|
||||||
|
const payment={id:'P1',mpId:'ORD1',status:'pending',profile:'pix-1h',uptime:'1h'};
|
||||||
|
const svc=paymentService({getDb:()=>({}),saveDb:()=>{},getPaymentStatus:async()=>{queries++;await new Promise(r=>setTimeout(r,10));return 'approved';},rosCommand:async()=>[],createHotspotUser:async()=>{creates++;}});
|
||||||
|
await Promise.all(Array.from({length:10},()=>svc.checkPayment(payment)));
|
||||||
|
assert.equal(queries,1);assert.equal(creates,1);assert.equal(payment.status,'paid');
|
||||||
|
});
|
||||||
|
test('RouterOS timeout retries reuse the persisted username without duplicating the voucher', async () => {
|
||||||
|
let created=null, calls=0;
|
||||||
|
const payment={id:'P2',mpId:'ORD2',status:'pending',profile:'pix-1h',uptime:'1h'};
|
||||||
|
const svc=paymentService({getDb:()=>({}),saveDb:()=>{},getPaymentStatus:async()=> 'approved',rosCommand:async()=>created ? [['=comment=pix:P2']] : [],createHotspotUser:async name=>{created=name;calls++;throw new Error('timeout after create');}});
|
||||||
|
await svc.checkPayment(payment);assert.equal(payment.status,'pending');assert.ok(payment.provisioning);
|
||||||
|
await svc.checkPayment(payment);assert.equal(payment.status,'paid');assert.equal(payment.voucher.user,created);assert.equal(calls,1);
|
||||||
|
});
|
||||||
|
test('unconfirmed payments never provision users', async () => {
|
||||||
|
let creates=0;
|
||||||
|
const svc=paymentService({getDb:()=>({}),saveDb:()=>{},getPaymentStatus:async()=>{throw new Error('MP unavailable');},rosCommand:async()=>[],createHotspotUser:async()=>{creates++;}});
|
||||||
|
const p={id:'P3',mpId:'ORD3',status:'pending'};await svc.checkPayment(p);assert.equal(creates,0);assert.equal(p.status,'pending');
|
||||||
|
});
|
||||||
+11
-5
@@ -1,7 +1,7 @@
|
|||||||
# ============================================================
|
# ============================================================
|
||||||
# pix-hotspot — instalação em 1 clique
|
# pix-hotspot — instalação em 1 clique
|
||||||
# docker compose up -d
|
# docker compose up -d
|
||||||
# Tudo configurável fica AQUI (nenhum .env necessário).
|
# Credenciais no ambiente do host ou em .env (veja .env.example).
|
||||||
# ============================================================
|
# ============================================================
|
||||||
name: pix-hotspot
|
name: pix-hotspot
|
||||||
|
|
||||||
@@ -17,17 +17,23 @@ services:
|
|||||||
|
|
||||||
environment:
|
environment:
|
||||||
# ===== Mercado Pago (PIX) =====
|
# ===== Mercado Pago (PIX) =====
|
||||||
MP_ACCESS_TOKEN: "COLE_SEU_TOKEN_AQUI" # APP_USR-... (producao) ou TEST-... (sandbox)
|
MP_ACCESS_TOKEN: "${MP_ACCESS_TOKEN:?Defina MP_ACCESS_TOKEN no ambiente ou .env}"
|
||||||
MP_ENVIRONMENT: "sandbox" # sandbox | production
|
MP_ENVIRONMENT: "${MP_ENVIRONMENT:-sandbox}"
|
||||||
|
MP_PUBLIC_KEY: "${MP_PUBLIC_KEY:-}"
|
||||||
|
|
||||||
# ===== MikroTik =====
|
# ===== MikroTik =====
|
||||||
MIKROTIK_HOST: "192.168.3.81" # IP do hAP lite na sua rede
|
MIKROTIK_HOST: "192.168.3.81" # IP do hAP lite na sua rede
|
||||||
MIKROTIK_PORT: "8728"
|
MIKROTIK_PORT: "8728"
|
||||||
MIKROTIK_USER: "api-pix"
|
MIKROTIK_USER: "api-pix"
|
||||||
MIKROTIK_PASSWORD: "Pix-2026!"
|
MIKROTIK_PASSWORD: "${MIKROTIK_PASSWORD:?Defina MIKROTIK_PASSWORD no ambiente ou .env}"
|
||||||
MIKROTIK_SERVER: "guest-hotspot" # nome do servidor hotspot
|
MIKROTIK_SERVER: "guest-hotspot" # nome do servidor hotspot
|
||||||
|
|
||||||
# ===== Backend =====
|
# ===== Backend =====
|
||||||
PORT: "3000"
|
PORT: "3000"
|
||||||
BASE_URL: "https://hotspot.jf.eng.br"
|
BASE_URL: "https://hotspot.jf.eng.br"
|
||||||
ADMIN_TOKEN: "troque-este-token-aleatorio-grande"
|
ADMIN_TOKEN: "${ADMIN_TOKEN:?Defina ADMIN_TOKEN com pelo menos 32 caracteres aleatorios}"
|
||||||
|
MP_WEBHOOK_SECRET: "${MP_WEBHOOK_SECRET:-}"
|
||||||
|
TRUST_PROXY: "${TRUST_PROXY:-}"
|
||||||
|
HOTSPOT_IP: "10.10.10.1"
|
||||||
|
FREE_ACCESS_SECONDS: "120"
|
||||||
|
FREE_ACCESS_COOLDOWN_SECONDS: "300"
|
||||||
@@ -1,11 +1,5 @@
|
|||||||
# ============================================================
|
# Página do hotspot INCTG
|
||||||
# Página do Hotspot com botão "Pagar com PIX"
|
Envie hotspot-login.html para hotspot/login.html no Winbox > Files.
|
||||||
# Envie para o MikroTik: Winbox -> Files -> pasta hotspot/
|
Preserve o alogin.html padrão do RouterOS, que respeita o parâmetro dst.
|
||||||
# edite o IP abaixo antes de enviar
|
O domínio padrão é https://hotspot.jf.eng.br; ajuste se necessário.
|
||||||
# ============================================================
|
Veja README.md para instalação, migração e validação da rede.
|
||||||
# Alternativa: use a pagina padrao do hotspot e adicione o link:
|
|
||||||
# http://SEU_IP_ZIMASOS:3000/?mac=$(mac)
|
|
||||||
#
|
|
||||||
# No Winbox: IP -> Hotspot -> Server -> aba HTTP ->
|
|
||||||
# ou edite hotspot/login.html direto no Files
|
|
||||||
# ============================================================
|
|
||||||
+52
-70
@@ -1,80 +1,62 @@
|
|||||||
# ============================================================
|
# INCTG - fresh installation, RouterOS 6.43+ with legacy wireless.
|
||||||
# pix-hotspot - Setup MikroTik hAP lite
|
# Export a backup and use Safe Mode. Do not import over an existing hotspot.
|
||||||
# WiFi de convidados isolado + Hotspot + perfis PIX
|
|
||||||
# Importe via: /import file-name=setup-hotspot.rsc
|
|
||||||
# (ou cole linha a linha no Terminal do Winbox)
|
|
||||||
# ============================================================
|
|
||||||
|
|
||||||
# ===== EDITAR ABAIXO =====
|
|
||||||
:local guestSubnet "10.10.10.0/24"
|
:local guestSubnet "10.10.10.0/24"
|
||||||
:local guestIP "10.10.10.1"
|
:local guestIP "10.10.10.1"
|
||||||
:local backendIP "192.168.3.100"
|
:local backendIP "192.168.3.100"
|
||||||
|
:local portalHost "hotspot.jf.eng.br"
|
||||||
:local wanInterface "ether1"
|
:local wanInterface "ether1"
|
||||||
:local guestInterface "ether4"
|
:local guestInterface "ether4"
|
||||||
|
|
||||||
# ===== 1. REDE DOS CONVIDADOS (isolada) =====
|
# Abort before changes when resources conflict.
|
||||||
/interface bridge add name=bridge-guest comment="REDE CONVIDADOS"
|
:if ([:len [/interface bridge find name="bridge-guest"]] > 0) do={ :error "Existing guest bridge: manual migration required" }
|
||||||
/ip address add address=($guestIP . "/24") interface=bridge-guest
|
:if ([:len [/interface bridge port find interface=$guestInterface]] > 0) do={ :error "Guest port is in another bridge: review topology in Safe Mode" }
|
||||||
|
:if ([:len [/ip hotspot find name="guest-hotspot"]] > 0) do={ :error "Existing guest hotspot: manual migration required" }
|
||||||
|
:if ([:len [/ip pool find name="guest-pool"]] > 0) do={ :error "Existing guest pool" }
|
||||||
|
:if ([:len [/ip hotspot profile find name="hs-guest"]] > 0) do={ :error "Existing hotspot profile" }
|
||||||
|
:if ([:len [/interface wireless find name="wlan1"]] = 0) do={ :error "Legacy wlan1 is required" }
|
||||||
|
:if ([:len [/interface find name=$wanInterface]] = 0) do={ :error "WAN not found" }
|
||||||
|
:if ([:len [/interface find name=$guestInterface]] = 0) do={ :error "Guest interface not found" }
|
||||||
|
|
||||||
# ether4 = porta fisica dos convidados (opcional - cabo para switch guest)
|
/interface bridge add name=bridge-guest comment="pix: guest network"
|
||||||
/interface bridge port add bridge=bridge-guest interface=$guestInterface comment="porta convidados"
|
/ip address add address=($guestIP . "/24") interface=bridge-guest comment="pix: guest gateway"
|
||||||
|
/interface bridge port add bridge=bridge-guest interface=$guestInterface
|
||||||
|
/interface wireless add master-interface=wlan1 name=wlan-guest ssid="Internet Gratis" mode=ap-bridge default-forwarding=no disabled=no
|
||||||
|
/interface bridge port add bridge=bridge-guest interface=wlan-guest
|
||||||
|
/ip pool add name=guest-pool ranges="10.10.10.10-10.10.10.50"
|
||||||
|
/ip dhcp-server add name=guest-dhcp interface=bridge-guest address-pool=guest-pool lease-time=1h disabled=no
|
||||||
|
/ip dhcp-server network add address=$guestSubnet gateway=$guestIP dns-server=1.1.1.1,8.8.8.8 comment="pix: DHCP"
|
||||||
|
/ip hotspot profile add name=hs-guest hotspot-address=$guestIP html-directory=hotspot login-by=cookie,http-chap,http-pap dns-name=""
|
||||||
|
/ip hotspot add name=guest-hotspot interface=bridge-guest address-pool=guest-pool profile=hs-guest disabled=no
|
||||||
|
|
||||||
# WiFi virtual para convidados (SSID separado)
|
# RouterOS rate-limit is upload/download from the client perspective.
|
||||||
/interface wireless add master-interface=wlan1 name=wlan-guest ssid="Internet Gratis" mode=ap disabled=no comment="WiFi convidados"
|
# Preserve existing profiles and vouchers.
|
||||||
/interface bridge port add bridge=bridge-guest interface=wlan-guest comment="wifi convidados"
|
:if ([:len [/ip hotspot user profile find name="pix-1h"]] = 0) do={ /ip hotspot user profile add name=pix-1h rate-limit=1M/5M shared-users=1 }
|
||||||
|
:if ([:len [/ip hotspot user profile find name="pix-24h"]] = 0) do={ /ip hotspot user profile add name=pix-24h rate-limit=2M/8M shared-users=1 }
|
||||||
|
:if ([:len [/ip hotspot user profile find name="pix-7d"]] = 0) do={ /ip hotspot user profile add name=pix-7d rate-limit=3M/10M shared-users=1 }
|
||||||
|
/ip firewall nat add chain=srcnat out-interface=$wanInterface src-address=$guestSubnet action=masquerade comment="pix: NAT"
|
||||||
|
|
||||||
# ===== 2. POOL + HOTSPOT =====
|
# Private-network guard runs before existing accepts/fasttrack.
|
||||||
/ip pool add name=guest-pool ranges=($guestIP . "10-")($guestIP . "50")
|
# Internet returns to the ordinary chain so HotSpot filtering still applies.
|
||||||
/ip pool set [find name=guest-pool] ranges=("10.10.10.10-10.10.10.50")
|
/ip firewall filter add chain=pix-guest-forward dst-address=$backendIP protocol=tcp dst-port=3000 action=accept comment="pix: portal LAN"
|
||||||
|
/ip firewall filter add chain=pix-guest-forward dst-address=192.168.0.0/16 action=drop
|
||||||
|
/ip firewall filter add chain=pix-guest-forward dst-address=10.0.0.0/8 action=drop
|
||||||
|
/ip firewall filter add chain=pix-guest-forward dst-address=172.16.0.0/12 action=drop
|
||||||
|
/ip firewall filter add chain=pix-guest-forward dst-address=169.254.0.0/16 action=drop
|
||||||
|
/ip firewall filter add chain=pix-guest-forward action=return
|
||||||
|
/ip firewall filter add chain=forward in-interface=bridge-guest action=jump jump-target=pix-guest-forward place-before=0 comment="pix: guest isolation"
|
||||||
|
/ip firewall filter add chain=pix-guest-input protocol=udp dst-port=53,67,64872 action=accept
|
||||||
|
/ip firewall filter add chain=pix-guest-input protocol=tcp dst-port=53,64872-64875 action=accept
|
||||||
|
/ip firewall filter add chain=pix-guest-input action=drop
|
||||||
|
/ip firewall filter add chain=input in-interface=bridge-guest action=jump jump-target=pix-guest-input place-before=0 comment="pix: router guard"
|
||||||
|
|
||||||
/ip hotspot profile add name=hs-guest hotspot-interface=bridge-guest html-directory=hotspot login-by=cookie,http-chap,http-pap dns-name="" comment="perfil hotspot convidados"
|
# Restrict pre-login exception to the portal host, not all Cloudflare IPs.
|
||||||
/ip hotspot add name=guest-hotspot interface=bridge-guest address-pool=guest-pool profile=hs-guest lease-time=1h disabled=no
|
/ip hotspot walled-garden ip add dst-host=$portalHost dst-port=443 protocol=tcp action=accept comment="pix: public portal"
|
||||||
|
/ip hotspot walled-garden ip add dst-address=$backendIP dst-port=3000 protocol=tcp action=accept comment="pix: local portal"
|
||||||
# ===== 3. PERFIS DE PLANO (nomes devem bater com o backend) =====
|
# HotSpot is IPv4-only: prevent an IPv6 path around authentication.
|
||||||
/ip hotspot user profile remove [find name~"pix-"]
|
:do {
|
||||||
/ip hotspot user profile add name=pix-1h rate-limit=5M/1M shared-users=1 comment="plano 1h"
|
/ipv6 firewall filter add chain=forward in-interface=bridge-guest action=drop place-before=0 comment="pix: block guest IPv6"
|
||||||
/ip hotspot user profile add name=pix-24h rate-limit=8M/2M shared-users=1 comment="plano 24h"
|
/ipv6 firewall filter add chain=input in-interface=bridge-guest action=drop place-before=0 comment="pix: block guest IPv6 management"
|
||||||
/ip hotspot user profile add name=pix-7d rate-limit=10M/3M shared-users=1 comment="plano 7d"
|
} on-error={ :log warning "pix: verify guest network has no IPv6 connectivity" }
|
||||||
|
# Copy hotspot-login.html ONLY to hotspot/login.html; keep stock alogin.html
|
||||||
# ===== 4. DNS/Internet dos convidados =====
|
# so the login dst parameter is honored. Restrict API service to backend LAN IP.
|
||||||
/ip firewall nat add chain=srcnat out-interface=$wanInterface src-address=$guestSubnet action=masquerade comment="NAT convidados"
|
:log info "pix-hotspot: setup complete; validate DHCP, DNS, login and isolation"
|
||||||
|
|
||||||
# ===== 5. FIREWALL - ISOLAMENTO =====
|
|
||||||
# Convidado pode ir: internet + backend (portal de pagamento) + DNS do hotspot
|
|
||||||
# Convidado NAO pode: rede interna192.168.3.0/24 (seus PCs, MikroTik, etc)
|
|
||||||
|
|
||||||
/ip firewall filter
|
|
||||||
# permite convidado -> backend:3000 (pagamento PIX)
|
|
||||||
add chain=forward src-address=$guestSubnet dst-address=$backendIP protocol=tcp dst-port=3000 action=accept place-before=0 comment="guest->backend PIX"
|
|
||||||
# permite respostas estabelecidas
|
|
||||||
add chain=forward connection-state=established,related action=accept place-before=0 comment="estabelecidos"
|
|
||||||
# BLOQUEIA convidado -> qualquer rede interna (exceto o backend ja aceito acima)
|
|
||||||
add chain=forward src-address=$guestSubnet dst-address=192.168.0.0/16 action=drop comment="guest nao acessa rede interna"
|
|
||||||
add chain=forward src-address=$guestSubnet dst-address=10.0.0.0/8 action=drop comment="guest nao acessa10.x"
|
|
||||||
add chain=forward src-address=$guestSubnet dst-address=172.16.0.0/12 action=drop comment="guest nao acessa172.x"
|
|
||||||
# gerenciao MikroTik pelo lado guest = bloqueado
|
|
||||||
add chain=input src-address=$guestSubnet dst-address=$guestIP action=drop comment="guest nao gerencia o MikroTik"
|
|
||||||
add chain=input src-address=$guestSubnet action=drop comment="guest so usa hotspot"
|
|
||||||
|
|
||||||
# ===== 6. WALLED GARDEN (portal antes do login) =====
|
|
||||||
# Portal publico (Cloudflare) - necessario para o convidado abrir o portal
|
|
||||||
# antes de autenticar. As faixas cobrem os IPs anycast usados pelo dominio.
|
|
||||||
/ip hotspot walled-garden ip
|
|
||||||
add dst-address=104.16.0.0/13 dst-port=443 protocol=tcp action=accept comment="pix-portal-cloudflare"
|
|
||||||
add dst-address=172.64.0.0/13 dst-port=443 protocol=tcp action=accept comment="pix-portal-cloudflare"
|
|
||||||
|
|
||||||
# Portal local (fallback, caso use o backend direto na LAN)
|
|
||||||
/ip hotspot walled-garden ip
|
|
||||||
add dst-address=192.168.3.100 dst-port=3000 protocol=tcp action=accept comment="pix: portal pagamento"
|
|
||||||
|
|
||||||
# ===== 6.1 PAGINA DE LOGIN CUSTOMIZADA =====
|
|
||||||
# Substituir hotspot/login.html e hotspot/alogin.html pelo arquivo
|
|
||||||
# mikrotik/hotspot-login.html (redireciona para o portal INCTG).
|
|
||||||
# Via FTP:
|
|
||||||
# curl -T hotspot-login.html ftp://USER:[email protected]/hotspot/login.html
|
|
||||||
# curl -T hotspot-login.html ftp://USER:[email protected]/hotspot/alogin.html
|
|
||||||
|
|
||||||
# ===== 7. LIMPA HOTSPOT ANTIGO (se houver) =====
|
|
||||||
/ip hotspot user remove [find where comment~"pix"]
|
|
||||||
|
|
||||||
:log info "pix-hotspot: setup de rede convidados concluido"
|
|
||||||
Reference in new issue
Block a user