Compare commits

..
Author SHA1 Message Date
jfeng 024adcb1cb Guide Wi-Fi purchase in four simple steps and configure LGPD notice with environment variables
build-image / build-push (push) Successful in 3m1s
2026-10-22 22:17:12 +00:00
jfeng ce6e5980ec Activate paid Wi-Fi automatically and redesign portal with payment deadline and 45-minute wait
build-image / build-push (push) Successful in 2m59s
2026-10-22 17:55:54 +00:00
jfeng b69b3afa5d Copy PIX successfully before granting internet and closing captive portal
build-image / build-push (push) Successful in 2m47s
2026-10-22 17:37:38 +00:00
jfeng 8d38a9136b Revalidate captive Wi-Fi with one portal navigation after API login
build-image / build-push (push) Successful in 2m44s
2026-10-22 17:23:16 +00:00
jfeng 4c7440e233 Fix browser connectivity probes rejected by Fetch no-cors redirect rules
build-image / build-push (push) Successful in 3m0s
2026-10-22 17:08:52 +00:00
jfeng 783e241e42 fix: start payment internet window on demand and verify connectivity from guest browser
build-image / build-push (push) Successful in 2m41s
2026-10-22 16:11:45 +00:00
15 changed files with 596 additions and 110 deletions

No files matched your search

+4
View File
@@ -6,3 +6,7 @@ MP_ENVIRONMENT=sandbox
MP_PUBLIC_KEY=
MP_WEBHOOK_SECRET=
TRUST_PROXY=
# Public privacy notice fields. Use the actual controller, contact and retention policy.
LGPD_RESPONSAVEL=
LGPD_CONTATO=
LGPD_RETENCAO=
+38 -9
View File
@@ -1,21 +1,50 @@
name: diagnose-hotspot-access
name: build-download
on:
workflow_dispatch:
permissions:
contents: read
jobs:
diagnose:
build-download:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Production diagnosis and database write check
- name: Checkout
uses: actions/checkout@v4
- name: Build image
run: |
docker build -t git.jf.eng.br/jfeng/hotspot:latest -t git.jf.eng.br/jfeng/hotspot:${{ github.sha }} ./backend
- name: Smoke test image
shell: bash
run: |
set -euo pipefail
docker inspect pix-hotspot --format 'IMAGE={{.Config.Image}} PORTS={{json .NetworkSettings.Ports}}'
docker exec -i pix-hotspot node --input-type=module < backend/diagnose-hotspot.mjs
- name: Recent sanitized errors
if: always()
container=$(docker run -d git.jf.eng.br/jfeng/hotspot:${{ github.sha }})
trap 'docker rm -f "$container" >/dev/null' EXIT
for attempt in {1..15}; do
if docker exec "$container" node -e "fetch('http://127.0.0.1:3000/api/health').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))"; then
docker exec "$container" node -e "Promise.all(['/api/plans','/admin'].map(p=>fetch('http://127.0.0.1:3000'+p).then(r=>{if(!r.ok)throw Error(p)}))).catch(()=>process.exit(1))"
exit 0
fi
sleep 1
done
docker logs "$container"
exit 1
- name: Export Docker archive
shell: bash
run: |
docker logs --since 2h --tail 3000 pix-hotspot 2>&1 | node -e 'let s="";process.stdin.on("data",x=>s+=x);process.stdin.on("end",()=>console.log(s.split("\n").filter(l=>/\[(ACESSO|CHECKOUT|LIMPEZA|HTTP)/.test(l)).slice(-60).map(l=>l.replace(/(?:[0-9a-f]{2}:){5}[0-9a-f]{2}/gi,"[MAC]").replace(/(?:\d{1,3}\.){3}\d{1,3}/g,"[IP]").replace(/(?:APP_USR|TEST)-[\w-]+/g,"[TOKEN]").replace(/[\w.+-]+@[\w.-]+\.[A-Za-z]{2,}/g,"[EMAIL]").slice(0,700)).join("\n")));'
set -euo pipefail
docker save git.jf.eng.br/jfeng/hotspot:latest git.jf.eng.br/jfeng/hotspot:${{ github.sha }} | gzip > pix-hotspot-image.tar.gz
sha256sum pix-hotspot-image.tar.gz > pix-hotspot-image.tar.gz.sha256
- name: Upload image for ZimaOS
uses: actions/upload-artifact@v3
with:
name: pix-hotspot-zimaos
path: |
pix-hotspot-image.tar.gz
pix-hotspot-image.tar.gz.sha256
retention-days: 7
+15 -6
View File
@@ -1,18 +1,20 @@
# INCTG — Wi-Fi com PIX
# INCTG — Wi-Fi com PIX
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.
## Fluxo
1. O MikroTik redireciona o convidado para o portal, com `?mac=...`.
2. O backend cria uma conta temporária vinculada ao MAC e tenta autenticar o dispositivo pela API `/ip/hotspot/active/login`. Confirma a sessão no roteador antes de mostrar o contador para abrir o aplicativo do banco (120 segundos; intervalo mínimo de 300 segundos). Se a API de login não estiver disponível, tenta a tela de login do hotspot; falhas ficam visíveis no portal e nos logs `[ACESSO]`/`[ACESSO LOGIN]`.
3. O comprador escolhe o plano, informa nome/e-mail e gera o PIX.
2. O comprador escolhe o plano, informa nome/e-mail e gera o PIX. O código fica visível, sem iniciar a liberação de internet nem navegar automaticamente.
3. A página guia a compra em quatro etapas: escolher o plano, informar quem paga, pagar e usar a internet. **Copiar código PIX** é a única ação para copiar e iniciar automaticamente o acesso temporário; não há botão separado para liberar internet. O prazo (padrão: 2 minutos), a espera e o possível fechamento da janela são explicados antes da cópia. Se a cópia falhar, a tela fica aberta e não inicia o prazo; é possível tentar o mesmo botão novamente. Apenas gerar ou restaurar um PIX não consome a janela. Sem pagamento confirmado, o acesso expira e o servidor exige pelo menos **45 minutos após o fim do prazo** antes de outra janela. `FREE_ACCESS_COOLDOWN_SECONDS` tem mínimo de 2700, inclusive em instalações antigas com valor 300; a espera é persistida no banco.
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.
5. O backend valida referência e valor pago e provisiona um voucher no MikroTik. Repetições reutilizam as credenciais persistidas.
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.
5. O backend valida referência e valor pago, provisiona um voucher e troca automaticamente a sessão temporária pelo plano comprado no mesmo aparelho. Confirma a sessão paga no MikroTik antes de antecipar a expiração temporária. Se a ativação falhar, mantém o pagamento aprovado e repete a conexão a cada 15 segundos, reutilizando o voucher. Uma conta paga diferente nunca é desconectada para essa troca.
6. A conexão paga funciona mesmo se a janela do portal já fechou. As credenciais continuam disponíveis como alternativa manual. Os limites são de **tempo acumulado de conexão**, não de validade corrida desde a compra.
## Instalação Docker
O aviso de privacidade pode ser alterado pelas variáveis públicas `LGPD_RESPONSAVEL` (nome/razão social de quem responde pela rede), `LGPD_CONTATO` (e-mail ou telefone para pedidos de titulares) e `LGPD_RETENCAO` (texto com os prazos reais de guarda por tipo de registro). Configure-as no ambiente do aplicativo ZimaOS ou no `.env` do Compose e reinicie/atualize o container. Não coloque senhas nessas variáveis: elas são publicadas em `/api/config`. Campos vazios orientam procurar o responsável no local. **`LGPD_RETENCAO` altera apenas o aviso, não implementa exclusão automática de registros**; os procedimentos de retenção, atendimento e bases legais devem corresponder à operação real. O aviso não constitui certificação de conformidade com a LGPD. Menores são orientados a pedir ajuda a um responsável para a compra.
1. Copie `.env.example` para `.env` no host Docker e preencha `MIKROTIK_PASSWORD` e `ADMIN_TOKEN`.
2. Configure `MP_ACCESS_TOKEN`, `BASE_URL`, IP/usuário/servidor MikroTik no `docker-compose.yml`. As credenciais reais devem permanecer exclusivamente no servidor.
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.
@@ -48,6 +50,7 @@ Usuários sem servidor específico ou com servidor `all` também aparecem: são
| `POST /api/checkout` | Público | `{planId, mac?, payerName, payerEmail, payerCpf?, deviceId?}` |
| `GET /api/status/:id` | ID aleatório da compra | Situação e voucher |
| `POST /api/access/start` | Público, limitado | Conta temporária para um MAC presente na rede |
| `POST /api/access/report` | Token da janela temporária | Registra o resultado dos testes externos no navegador; nunca libera nem estende acesso |
| `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 |
@@ -79,7 +82,13 @@ Os perfis `pix-1h`, `pix-24h`, `pix-7d` precisam existir no roteador. No RouterO
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.
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.
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 ou use `mikrotik/hotspot-alogin.html`, que respeita `$(link-redirect)`.
O walled garden e a exceção do firewall para o portal local devem usar a porta publicada no host ZimaOS. Por exemplo, se o mapeamento for `8905:3000`, os convidados acessam a porta **8905** do ZimaOS, embora o processo escute em 3000 dentro do container. Ajuste `backendPort` no script antes da instalação.
Depois de confirmar a sessão, o portal tenta consultar Google e Apple diretamente do navegador, sem enviar o MAC ou token da janela a esses destinos. Os resultados ficam no registro temporário e nos logs `[ACESSO CLIENTE]`. Esse é um diagnóstico do navegador: bloqueadores, falhas dos destinos ou uso de dados móveis podem interferir. Para validar especificamente o Wi-Fi, teste no aparelho com os dados móveis desligados.
Após a autenticação pela API, o portal faz uma navegação automática no próprio domínio uma vez por janela temporária. A tela de entrada de rede do Android reavalia a conectividade ao navegar; apenas atualizar o contador por JavaScript pode deixar o aparelho tratando o Wi-Fi como sem internet. O PIX continua no armazenamento da sessão, e o retorno reutiliza o prazo original do backend, sem renovar os dois minutos. A validação final deste comportamento precisa ser feita no celular, sem desconectar o Wi-Fi.
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.
-36
View File
@@ -1,36 +0,0 @@
import fs from 'node:fs';
import crypto from 'node:crypto';
import config from '/app/src/config.js';
import { rosCommand } from '/app/src/ros.js';
const hash=v=>crypto.createHash('sha256').update(String(v)).digest('hex').slice(0,10);
const redact=s=>String(s).replace(/(?:[0-9a-f]{2}:){5}[0-9a-f]{2}/gi,m=>'device-'+hash(m)).replace(/(?:\d{1,3}\.){3}\d{1,3}/g,m=>m.split('.').slice(0,3).join('.')+'.x');
const object=row=>Object.fromEntries(row.filter(v=>v[0]==='=').map(v=>{const i=v.indexOf('=',1);return [v.slice(1,i),v.slice(i+1)];}));
console.log('CONFIG',JSON.stringify({routerHost:config.mikrotik.host,routerPort:config.mikrotik.port,routerUser:config.mikrotik.user,server:config.mikrotik.server,hotspotIp:config.hotspotIp,baseUrl:config.baseUrl,port:config.port,freeSeconds:config.freeAccessSeconds,cooldown:config.freeAccessCooldownSeconds,processUid:fs.readFileSync('/proc/1/status','utf8').match(/^Uid:.*$/m)?.[0]}));
for(const [label,words] of [
['RESOURCE',['/system/resource/print','=.proplist=version,architecture-name,board-name']],
['HOTSPOTS',['/ip/hotspot/print','=.proplist=name,interface,profile,disabled']],
['HOTSPOT-PROFILES',['/ip/hotspot/profile/print','=.proplist=name,login-by,hotspot-address,dns-name,html-directory']],
['FREE-PROFILE',['/ip/hotspot/user/profile/print','?name=pix-free','=.proplist=.id,name,rate-limit,session-timeout,shared-users,add-mac-cookie']],
['API-USER',['/user/print','?name='+config.mikrotik.user,'=.proplist=name,group,disabled']],
['HOSTS',['/ip/hotspot/host/print','=.proplist=address,to-address,mac-address,server,authorized,bypassed']],
['ACTIVE',['/ip/hotspot/active/print','=.proplist=user,address,mac-address,server,uptime,session-time-left']],
['FREE-USERS',['/ip/hotspot/user/print','?profile=pix-free','=.proplist=name,server,profile,disabled,limit-uptime,uptime,mac-address']],
['FILTER',['/ip/firewall/filter/print','=.proplist=chain,action,disabled,comment,in-interface,out-interface,src-address,dst-address,protocol,dst-port,connection-state,jump-target']],
]) {
try {const rows=(await rosCommand(words)).map(object);console.log(label,redact(JSON.stringify(rows.map(r=>label==='ACTIVE'||label==='FREE-USERS'?{...r,user:r.user?'account-'+hash(r.user):undefined,name:r.name?'account-'+hash(r.name):undefined}:r))));}
catch(e){console.log(label+'-ERROR',redact(e.message));}
}
try {
const db=JSON.parse(fs.readFileSync(config.dataDir+'/db.json','utf8'));
console.log('TEMP-RECORDS',JSON.stringify((db.tempAccess||[]).map(t=>({device:hash(t.mac),createdAt:t.createdAt,expiresAt:t.expiresAt,revoked:t.revoked}))));
} catch(e){console.log('DB-ERROR',redact(e.message));}
const source="import net from 'node:net';\nimport config from 'file:///app/src/config.js';\nimport crypto from 'node:crypto';\n\nfunction packLen(n) {\n if (n < 0x80) return Buffer.from([n]);\n if (n < 0x4000) return Buffer.from([0x80 | (n >> 8), n & 0xff]);\n if (n < 0x200000) return Buffer.from([0xc0 | (n >> 16), (n >> 8) & 0xff, n & 0xff]);\n if (n < 0x10000000) return Buffer.from([0xe0 | (n >> 24), (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]);\n return Buffer.from([0xf0, (n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]);\n}\n\nfunction encodeSentence(words) {\n const parts = [];\n for (const w of words) {\n const buf = Buffer.from(String(w), 'utf8');\n parts.push(packLen(buf.length), buf);\n }\n parts.push(Buffer.from([0]));\n return Buffer.concat(parts);\n}\n\nclass Parser {\n constructor() {\n this.buf = Buffer.alloc(0);\n this.words = [];\n this.sentence = [];\n this.done = false;\n this.error = null;\n this.replies = [];\n }\n push(chunk) {\n this.buf = Buffer.concat([this.buf, chunk]);\n if (this.buf.length > 8 * 1024 * 1024) { this.error = 'Resposta RouterOS excede o limite'; return; }\n while (true) {\n if (this.buf.length === 0) return;\n const first = this.buf[0];\n let len, offset;\n if ((first & 0x80) === 0) { len = first; offset = 1; }\n else if ((first & 0xc0) === 0x80) {\n if (this.buf.length < 2) return;\n len = ((first & 0x3f) << 8) | this.buf[1]; offset = 2;\n } else if ((first & 0xe0) === 0xc0) {\n if (this.buf.length < 3) return;\n len = ((first & 0x1f) << 16) | (this.buf[1] << 8) | this.buf[2]; offset = 3;\n } else if ((first & 0xf0) === 0xe0) {\n if (this.buf.length < 4) return;\n len = ((first & 0x0f) << 24) | (this.buf[1] << 16) | (this.buf[2] << 8) | this.buf[3]; offset = 4;\n } else if (first === 0xf0) {\n if (this.buf.length < 5) return;\n len = (this.buf[1] << 24) | (this.buf[2] << 16) | (this.buf[3] << 8) | this.buf[4]; offset = 5;\n } else { this.error = 'Comprimento RouterOS inválido'; return; }\n if (len < 0 || len > 8 * 1024 * 1024) { this.error = 'Resposta RouterOS inválida'; return; }\n if (this.buf.length < offset + len) return;\n const data = this.buf.subarray(offset, offset + len);\n this.buf = this.buf.subarray(offset + len);\n if (len === 0) {\n if (this.sentence.length > 0) {\n this.handleSentence(this.sentence);\n this.sentence = [];\n } else if (this.words.length > 0) {\n this.handleSentence(this.words);\n this.words = [];\n }\n if (this.done || this.error) return;\n } else {\n this.words.push(data.toString('utf8'));\n }\n }\n }\n handleSentence(words) {\n const attr = words[0];\n if (attr === '!re') this.replies.push(words.slice(1));\n else if (attr === '!done') this.done = true;\n else if (attr === '!trap') this.error = words.slice(1).join(' ') || 'trap';\n else if (attr === '!fatal') this.error = 'RouterOS encerrou a conexão';\n else this.replies.push(words);\n }\n}\n\nexport async function rosCommand(words, timeoutMs = 8000) {\n return new Promise((resolve, reject) => {\n const socket = new net.Socket();\n const parser = new Parser();\n let settled = false;\n const finish = (err, val) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n socket.destroy();\n err ? reject(err) : resolve(val);\n };\n const timer = setTimeout(() => finish(new Error('timeout MikroTik API')), timeoutMs);\n socket.on('error', (e) => finish(e));\n socket.on('close', () => {\n if (!settled) finish(new Error('conexao MikroTik fechada'));\n });\n socket.connect(config.mikrotik.port, config.mikrotik.host, () => {\n socket.write(encodeSentence(['/login', `=name=${config.mikrotik.user}`, `=password=${config.mikrotik.password}`]));\n const onLogin = (chunk) => {\n parser.push(chunk);\n if (parser.error) { socket.off('data', onLogin); return finish(new Error(parser.error)); }\n if (parser.done) {\n socket.off('data', onLogin);\n // login ok - recria parser e envia comando\n const p2 = new Parser();\n const onData2 = (c2) => {\n p2.push(c2);\n if (p2.error) finish(new Error(p2.error));\n else if (p2.done) finish(null, p2.replies);\n };\n socket.on('data', onData2);\n socket.write(encodeSentence(words));\n } else if (parser.replies.length && parser.replies.some(r => r.some(w => w.startsWith('=ret=')))) {\n finish(new Error('RouterOS antigo (<6.43): use login simples - atualize o RouterOS'));\n }\n };\n socket.on('data', onLogin);\n });\n });\n}\n\nexport async function createHotspotUser(name, password, profile, uptime, comment = 'pix:manual') {\n const words = [\n Line truncated
const {activatePaidAccess}=await import('data:text/javascript;base64,'+Buffer.from(source).toString('base64'));
const db=JSON.parse(fs.readFileSync(config.dataDir+'/db.json','utf8'));
const payment=db.payments.filter(p=>p.status==='paid'&&p.voucher&&p.mac&&Date.parse(p.paidAt)>Date.now()-24*3600000).at(-1);
if(payment){
console.log('PAID-HANDOFF-RESULT',JSON.stringify({device:hash(payment.mac),active:await activatePaidAccess(payment)}));
const active=(await rosCommand(['/ip/hotspot/active/print','?mac-address='+payment.mac])).map(object);
console.log('PAID-HANDOFF-SESSION',JSON.stringify(active.map(a=>({device:hash(a['mac-address']),paidUser:a.user===payment.voucher.user,server:a.server,uptime:a.uptime,remaining:a['session-time-left']}))));
}else console.log('NO-RECENT-PAID-PAYMENT');
+196 -37
View File
@@ -6,9 +6,6 @@
<meta name="theme-color" content="#101820">
<title>INCTG Wi-Fi Convidados</title>
<link rel="icon" type="image/png" href="logo.png">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Manrope:wght@500;600;700;800&family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
<!-- Mercado Pago: SDK JS V2 + Device ID (gera MP_DEVICE_SESSION_ID) -->
<script src="https://sdk.mercadopago.com/js/v2" defer></script>
<script src="https://www.mercadopago.com.br/integrations/v1/security-code.js" async view="checkout"></script>
@@ -464,6 +461,44 @@
}
@keyframes sk { to { background-position: -200% 0; } }
/* Mobile portal: readable rules, clear steps, and one primary payment action. */
:root { --radius-sm:12px; --radius-md:18px; --radius-lg:24px; --gray:#a3b3c7; --blue:#568aff; --blue-hover:#73a0ff; }
body { background:#0a1220; padding-top:32px; }
.wrap { max-width:500px; gap:18px; }
.brand { align-items:flex-start; text-align:left; gap:20px; padding:8px 4px 12px; }
.brand-logo { width:68px; border-radius:18px; }
.brand h1 { font-size:2.25rem; line-height:1.1; letter-spacing:-.045em; margin:10px 0; }
.brand .tagline { line-height:1.7; max-width:35ch; }
.eyebrow { color:#a7c2ff; text-transform:uppercase; font-size:.7rem; letter-spacing:.18em; font-weight:700; }
.journey { display:flex; gap:8px; margin-top:16px; flex-wrap:wrap; }
.journey span { font-size:.73rem; color:#c2cee0; border:1px solid var(--line); padding:7px 11px; border-radius:50px; }
.card { background:linear-gradient(145deg,#172438,#101b2b); border-color:rgba(164,190,230,.14); box-shadow:0 16px 40px #0002; padding:24px; }
.access-card { border-color:#f3bb5755; background:linear-gradient(135deg,#30291d,#191e29); }
.access-heading { display:flex; flex-wrap:wrap; justify-content:space-between; align-items:center; gap:12px; margin-bottom:12px; }
.access-heading strong { color:#ffda97; font-size:.9rem; }
.countdown { color:#ffe4b2; font-size:1.5rem; font-weight:800; font-variant-numeric:tabular-nums; }
.access-rules { color:#e5d9c5; font-size:.84rem; line-height:1.7; }
.consent { display:flex; align-items:flex-start; gap:10px; margin-top:16px; padding-top:14px; border-top:1px solid #f3bb572b; color:#f3e6d0; font-size:.8rem; line-height:1.6; cursor:pointer; }
.consent input { flex-shrink:0; width:19px; height:19px; margin-top:3px; accent-color:#568aff; }
#freeAccessMessage { margin-top:14px; color:#c2cee0; font-size:.83rem; line-height:1.6; }
#freeAccessProbe { font-size:.75rem; color:var(--gray); margin-top:10px; }
.how-to { padding-left:22px; color:#d7e3f5; line-height:1.7; font-size:.9rem; }
.how-to li { margin-bottom:10px; padding-left:4px; }
.step-label { color:#a7c2ff; font-size:.75rem; font-weight:700; margin-bottom:8px; }
.privacy { font-size:.8rem; line-height:1.7; color:#bac8db; }
.privacy summary { cursor:pointer; color:#dbe8ff; padding:12px 0; font-weight:600; }
.privacy p { margin-bottom:12px; }
.privacy a { color:#9cbeff; }
.payment-note { margin:16px 0; padding:14px; border:1px solid #f3bb5755; border-radius:14px; background:#30291d; }
.plan { padding:20px 16px; }
.btn { min-height:48px; border-radius:14px; }
#copyBtn { background:#568aff; color:#fff; border:0; flex:1 1 100%; }
#view-pay .row { flex-wrap:wrap; }
.pay-head p, .hint { line-height:1.7; }
.qr-panel { background:#fff; border-radius:20px; }
.copia { font-family:ui-monospace,monospace; font-size:.76rem; max-height:95px; overflow:auto; user-select:all; }
@media (max-width:360px) { .card { padding:18px; } .brand h1 { font-size:1.9rem; } }
@media (prefers-reduced-motion:reduce) { *, *::before, *::after { animation:none!important; transition:none!important; scroll-behavior:auto!important; } }
</style>
</head>
<body>
@@ -471,19 +506,24 @@
<header class="brand">
<img class="brand-logo" src="logo.png" alt="INCTG — Incorpore Technology Group" width="108" height="108">
<div>
<h1>Wi-Fi Convidados</h1>
<p class="tagline">Escolha seu plano · <strong>Pague com PIX</strong> · Conecte em segundos</p>
<div class="eyebrow">INCTG · Wi-Fi para você</div>
<h1>Vamos conectar<br>seu Wi-Fi?</h1>
<p class="tagline" id="flowHelp">Primeiro, escolha por quanto tempo você quer usar a internet.</p>
<div class="journey" aria-label="Etapas"><span id="step-plans">1 · Escolher</span><span id="step-payer">2 · Preencher</span><span id="step-pay">3 · Pagar</span><span id="step-voucher">4 · Usar</span></div>
</div>
</header>
<!-- ===== PLANOS ===== -->
<div class="card" style="margin-bottom:14px" role="status" aria-live="polite">
<p id="freeAccessMessage">Verificando acesso temporário para pagamento…</p>
<button class="btn btn-ghost" id="retryFreeAccess" type="button" hidden>Tentar liberar acesso</button>
<div class="card">
<div class="access-heading"><strong>Seu Wi-Fi</strong><span id="freeCountdown" class="countdown" role="timer" aria-label="Tempo restante"></span></div>
<p id="freeAccessMessage" role="status" aria-live="polite">Preparando seu acesso…</p>
<p id="freeAccessProbe" hidden></p>
<a id="wifiEntry" href="http://10.10.10.1/login" hidden>Abrir a entrada do Wi-Fi</a>
</div>
<main id="view-plans">
<div class="card">
<div class="section-label">Planos disponíveis</div>
<div class="step-label">PASSO 1 DE 4</div>
<div class="section-label">Escolha seu plano</div>
<div id="plans">
<div class="skel"></div><div class="skel"></div><div class="skel"></div>
</div>
@@ -508,8 +548,9 @@
<!-- ===== DADOS DO PAGADOR ===== -->
<section id="view-payer" class="card hidden" aria-labelledby="payerTitle">
<div class="pay-head">
<h2 id="payerTitle">Seus dados</h2>
<p>Para emissão do PIX, informe seu nome e e-mail</p>
<div class="step-label">PASSO 2 DE 4</div>
<h2 id="payerTitle">Quem vai pagar?</h2>
<p>Digite o nome e o e-mail de quem fará o pagamento.</p>
</div>
<label class="field">
@@ -526,15 +567,25 @@
<button class="btn btn-ghost" id="payerBack" type="button">← Voltar</button>
<button class="btn btn-primary" id="payerNext" type="button">Gerar PIX</button>
</div>
<p class="hint" style="margin-top:16px">É menor de idade? Peça a um responsável para preencher os dados e fazer o pagamento. Veja abaixo como seus dados são usados.</p>
</section>
<!-- ===== PAGAMENTO ===== -->
<section id="view-pay" class="card hidden" aria-labelledby="payTitle">
<div class="pay-head">
<h2 id="payTitle">PIX</h2>
<p>Escaneie o QR Code no app do seu banco</p>
<div class="step-label">PASSO 3 DE 4</div>
<h2 id="payTitle">Pague com PIX</h2>
<p>Faça assim:</p>
</div>
<ol class="how-to">
<li>Toque em <strong>Copiar código PIX</strong>.</li>
<li>Abra o aplicativo do seu banco.</li>
<li>Escolha <strong>PIX → Copia e Cola</strong>, cole o código e confirme o pagamento.</li>
<li>Pronto! Quando o pagamento for confirmado, seu plano começa automaticamente.</li>
</ol>
<div class="payment-note"><p id="accessRules" class="access-rules">Ao copiar, você terá 2 minutos de internet para pagar. Se o prazo acabar sem confirmação do pagamento, a internet para. Uma nova tentativa só será possível 45 minutos depois.</p><p class="access-rules" style="margin-top:8px">A janela pode fechar depois da cópia. Tudo bem: abra seu banco e cole o código.</p></div>
<div class="qr-panel">
<img id="qrImg" alt="QR Code do pagamento PIX">
</div>
@@ -542,7 +593,7 @@
<div class="copia" id="copiaCola" title="Código copia e cola"></div>
<div class="row">
<button class="btn btn-ghost" id="copyBtn" type="button">Copiar código</button>
<button class="btn btn-ghost" id="copyBtn" type="button">Copiar código PIX</button>
<button class="btn btn-primary" id="checkBtn" type="button">Já paguei</button>
</div>
@@ -568,8 +619,9 @@
<polyline points="20 6 9 17 4 12"></polyline>
</svg>
</div>
<h2 id="vTitle">Pagamento confirmado</h2>
<p class="hint">Use os dados abaixo na tela de login do Wi-Fi.</p>
<div class="step-label">PASSO 4 DE 4</div>
<h2 id="vTitle">Tudo pronto!</h2>
<p class="hint" id="paidConnectionMessage">Conectando seu aparelho ao plano comprado…</p>
<div class="code-box">
<div class="lbl">Usuário</div>
@@ -581,9 +633,9 @@
</div>
<ol class="steps">
<li>Toque no botão <strong>Conectar agora</strong> abaixo</li>
<li>Se pedir, conecte na rede <strong id="ssidLabel">Wi-Fi</strong></li>
<li>Pronto: seu acesso já estará liberado</li>
<li>Seu pagamento foi confirmado</li>
<li>Mantenha o aparelho na rede <strong id="ssidLabel">Wi-Fi</strong></li>
<li>A conexão muda automaticamente para o plano comprado</li>
</ol>
<button class="btn btn-success" id="hsAutoLogin" type="button" style="margin-top:14px">Conectar agora</button>
@@ -591,6 +643,18 @@
<a class="back" href="#" id="backBtn2">← Voltar aos planos</a>
</section>
<details class="card privacy" id="privacyNotice">
<summary>Seus dados e sua privacidade (LGPD)</summary>
<p><strong>Responsável pelo Wi-Fi:</strong> <span id="privacyController">Procure o responsável por esta rede no local.</span><br><strong>Fale sobre seus dados:</strong> <span id="privacyContact">Solicite o contato ao responsável pelo Wi-Fi.</span></p>
<p>Usamos nome e e-mail de quem paga para criar o PIX no Mercado Pago. O identificador do aparelho (MAC), o plano, o valor, os horários e a situação do pagamento são usados para conectar o Wi-Fi e evitar uso indevido.</p>
<p>O Mercado Pago recebe os dados necessários ao pagamento e pode coletar informações do dispositivo para segurança e prevenção de fraude. Você paga dentro do aplicativo do seu banco. Este portal não pede sua senha do banco.</p>
<p>Para verificar se a internet funciona, seu navegador pode consultar Google e Apple. Essas consultas usam os dados normais de uma conexão, como o endereço IP. O portal não envia seu nome, e-mail, código PIX ou identificador MAC nesses testes.</p>
<p>O navegador guarda os dados do PIX nesta sessão para você continuar de onde parou. Os registros de compra e acesso ficam no sistema da rede para operar o serviço, atender solicitações e cumprir obrigações aplicáveis.</p>
<p><strong>Por quanto tempo guardamos:</strong> <span id="privacyRetention">Peça ao responsável pelo Wi-Fi os prazos aplicáveis a cada tipo de registro.</span></p>
<p>Você pode pedir informações sobre seus dados, acesso, correção e exclusão quando cabível. Procure o responsável pelo Wi-Fi neste local para exercer esses direitos e saber os prazos de guarda. A LGPD não exige apagar registros que precisam ser mantidos por obrigação legal.</p>
<p>Crianças e adolescentes: os dados devem ser tratados respeitando seu melhor interesse. Peça ajuda a um responsável para a compra; este aviso não substitui os cuidados e autorizações que forem necessários.</p>
<p><a href="https://www.gov.br/anpd/pt-br/assuntos/titular-de-dados/direito-dos-titulares" target="_blank" rel="noopener noreferrer">Conheça seus direitos na ANPD</a> · <a href="https://www.mercadopago.com.br/privacidade" target="_blank" rel="noopener noreferrer">Privacidade do Mercado Pago</a></p>
</details>
<footer>
<strong>INCTG</strong> — Incorpore Technology Group<br>
Tecnologia que resolve.
@@ -607,6 +671,15 @@
let selectedPlanId = null;
let mpDevice = null;
let checkoutBusy = false;
let freeSeconds = 120;
let freeCooldownSeconds = 2700;
function durationLabel(seconds) {
return seconds % 60 === 0 ? (seconds / 60) + (seconds === 60 ? ' minuto' : ' minutos') : seconds + (seconds === 1 ? ' segundo' : ' segundos');
}
function renderAccessRules() {
$('accessRules').textContent = 'Ao tocar em “Copiar código PIX”, você terá ' + durationLabel(freeSeconds) + ' de internet para pagar. Se o prazo acabar sem confirmação do pagamento, a internet para. Uma nova tentativa só será possível ' + durationLabel(freeCooldownSeconds) + ' após o fim desse prazo. Pagamento confirmado? Seu plano começa automaticamente.';
}
const $ = (id) => document.getElementById(id);
@@ -640,19 +713,30 @@
async function copy(text, msg) {
try {
await navigator.clipboard.writeText(text);
toast(msg || 'Copiado!');
} catch {
const ta = document.createElement('textarea');
ta.value = text;
document.body.appendChild(ta);
ta.select();
document.execCommand('copy');
ta.remove();
toast(msg || 'Copiado!');
try {
if (!document.execCommand('copy')) throw new Error('Clipboard unavailable');
} catch {
toast('Não foi possível copiar. Selecione e copie o código manualmente.');
return false;
} finally { ta.remove(); }
}
toast(msg || 'Copiado!');
return true;
}
function show(view) {
const help = {plans:'Escolha por quanto tempo você quer usar a internet.',payer:'Preencha os dados de quem vai pagar.',pay:'Copie o código, abra seu banco e pague com PIX.',voucher:'Seu pagamento foi confirmado. Agora é só navegar.'};
$('flowHelp').textContent = help[view];
for (const step of ['plans','payer','pay','voucher']) {
if (step === view) $('step-' + step).setAttribute('aria-current','step');
else $('step-' + step).removeAttribute('aria-current');
$('step-' + step).style.background = step === view ? '#244b8c' : '';
}
$('view-plans').classList.toggle('hidden', view !== 'plans');
$('view-payer').classList.toggle('hidden', view !== 'payer');
$('view-pay').classList.toggle('hidden', view !== 'pay');
@@ -714,6 +798,7 @@
currentPaymentId = data.paymentId;
sessionStorage.setItem('paymentId', currentPaymentId);
sessionStorage.setItem('pendingPix', JSON.stringify(data));
$('payTitle').textContent = data.planName + ' · ' + money(data.price);
$('qrImg').src = data.qrCodeBase64 ? 'data:image/png;base64,' + data.qrCodeBase64 : '';
$('copiaCola').textContent = data.copiaCola || '';
@@ -722,6 +807,7 @@
clearInterval(pollTimer);
pollTimer = setInterval(verify, 6000);
$('freeAccessMessage').textContent = 'PIX pronto. Agora toque em “Copiar código PIX”. Depois, abra o banco e cole o código.';
} catch (e) {
toast('Erro: ' + e.message);
} finally {
@@ -745,11 +831,19 @@
if (!res.ok) throw new Error('Falha na consulta');
const data = await res.json();
if (data.status === 'paid' && data.voucher) {
sessionStorage.removeItem('pendingPix');
clearInterval(window.freeAccessTimer);
const connected = data.connection?.state === 'active';
$('hsAutoLogin').hidden = connected;
$('freeAccessMessage').textContent = connected ? 'Pagamento confirmado. Seu plano está conectado. Boa navegação!' : 'Pagamento confirmado. Estamos conectando seu aparelho ao plano comprado.';
$('paidConnectionMessage').textContent = connected ? 'Seu plano está ativo neste aparelho. Você já pode navegar.' : 'Ativando sua conexão automaticamente. Se necessário, use “Conectar agora”.';
$('freeCountdown').textContent = connected ? 'Conectado' : 'Ativando';
clearInterval(pollTimer); pollTimer = null;
$('vUser').textContent = data.voucher.user;
$('vPass').textContent = data.voucher.pass;
setPill('ok', 'Pagamento aprovado');
show('voucher');
if (!connected) pollTimer = setInterval(verify, 6000);
return;
}
if (['rejected', 'cancelled', 'expired'].includes(data.status)) {
@@ -766,7 +860,17 @@
}
$('checkBtn').addEventListener('click', verify);
$('copyBtn').addEventListener('click', () => copy($('copiaCola').textContent, 'Código PIX copiado'));
$('copyBtn').addEventListener('click', async () => {
const button = $('copyBtn');
if (button.disabled) return;
const code = $('copiaCola').textContent.trim();
if (!code) { toast('O código PIX ainda não está disponível.'); return; }
if (!/^([0-9a-f]{2}:){5}[0-9a-f]{2}$/i.test(mac)) { await startFreeAccess(); return; }
button.disabled = true;
try {
if (await copy(code, 'PIX copiado. Abra o banco e cole o código.')) await startFreeAccess();
} finally { button.disabled = false; }
});
$('copyVoucher').addEventListener('click', () =>
copy('Usuário: ' + $('vUser').textContent + '\nSenha: ' + $('vPass').textContent, 'Credenciais copiadas')
);
@@ -809,12 +913,11 @@
// ===== Internet temporaria para pagar (login automatico no hotspot) =====
async function startFreeAccess() {
const message = $('freeAccessMessage');
const retry = $('retryFreeAccess');
if (!/^([0-9a-f]{2}:){5}[0-9a-f]{2}$/i.test(mac)) {
message.textContent = 'Para liberar internet temporária, conecte ao Wi-Fi de convidados e abra o portal pela tela de entrada da rede.';
$('wifiEntry').hidden = false;
return;
}
retry.hidden = true;
message.textContent = 'Preparando acesso temporário para abrir o aplicativo do banco…';
try {
const res = await fetch('/api/access/start', {
@@ -824,53 +927,109 @@
});
const d = await res.json();
if (!res.ok) {
message.textContent = res.status === 429 ? d.error + (d.retryAfterSeconds ? ' Tente em ' + d.retryAfterSeconds + ' segundos.' : '') : 'Não foi possível liberar a internet temporária. Tente novamente ou consulte o responsável pela rede.';
retry.hidden = false;
message.textContent = res.status === 429 ? d.error + (d.retryAfterSeconds ? ' Nova liberação em aproximadamente ' + Math.ceil(d.retryAfterSeconds / 60) + ' minutos.' : '') : 'Não foi possível liberar a internet temporária. Tente novamente ou consulte o responsável pela rede.';
return;
}
if (d.authenticated) {
// Captive-portal assistants re-evaluate the network on top-level navigation.
// An API login plus a DOM update leaves some phones using the captive state.
// Navigate once per server window; reloading must never extend its deadline.
if (Number.isFinite(d.expiresAt) && d.expiresAt > Date.now() &&
sessionStorage.getItem('freeAccessConfirmedUntil') !== String(d.expiresAt)) {
sessionStorage.setItem('freeAccessConfirmedUntil', String(d.expiresAt));
const target = new URL(location.href);
target.searchParams.set('mac', mac);
target.searchParams.set('free', '1');
target.searchParams.set('access', String(d.expiresAt));
message.textContent = 'Acesso autorizado. Atualizando a conexão deste aparelho…';
window.location.replace(target.href);
return;
}
if (d.probeToken) verifyClientInternet(d.probeToken);
sessionStorage.removeItem('freeLoginAttemptUntil');
clearInterval(window.freeAccessTimer);
const deadline = Date.now() + d.seconds * 1000;
const update = () => {
const seconds = Math.max(0, Math.ceil((deadline - Date.now()) / 1000));
$('freeCountdown').textContent = Math.floor(seconds / 60) + ':' + String(seconds % 60).padStart(2, '0');
message.textContent = seconds ? 'Sessão temporária confirmada: ' + seconds + ' segundos para efetuar o pagamento.' : 'O acesso temporário terminou. Se já pagou, toque em “Já paguei”.';
if (!seconds) { clearInterval(window.freeAccessTimer); retry.hidden = false; }
if (!seconds) message.textContent += ' Para solicitar mais tempo, aguarde ' + durationLabel(freeCooldownSeconds) + '. O pagamento confirmado ativa o plano automaticamente.';
if (!seconds) clearInterval(window.freeAccessTimer);
};
update(); window.freeAccessTimer = setInterval(update, 1000);
return;
}
message.textContent = 'O MikroTik ainda não confirmou o acesso. Tentando autenticar pela tela do hotspot…';
retry.hidden = false;
if (d.loginUrl && Number(sessionStorage.getItem('freeLoginAttemptUntil') || 0) < Date.now()) {
sessionStorage.setItem('freeLoginAttemptUntil', String(Date.now() + d.seconds * 1000));
const target = new URL(d.loginUrl);
hotspotLogin(target.searchParams.get('username'), target.searchParams.get('password'), target.searchParams.get('dst'));
}
} catch {
message.textContent = 'Falha ao verificar o acesso temporário. Toque em tentar liberar acesso.';
retry.hidden = false;
message.textContent = 'Não conseguimos conectar agora. Toque novamente em “Copiar código PIX” para tentar de novo.';
}
}
$('retryFreeAccess').addEventListener('click', () => {
sessionStorage.removeItem('freeLoginAttemptUntil');
startFreeAccess();
});
async function verifyClientInternet(token) {
const label = $('freeAccessProbe');
label.hidden = false;
label.textContent = 'Verificando o acesso a serviços externos neste aparelho…';
const results = await Promise.all([
['google', 'https://www.gstatic.com/generate_204'],
['apple', 'https://www.apple.com/library/test/success.html'],
].map(async ([provider, url]) => {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 6000);
try {
const response = await fetch(url + '?_=' + Date.now(), { mode: 'no-cors', cache: 'no-store', redirect: 'follow', credentials: 'omit', signal: controller.signal });
return { provider, ok: response.type === 'opaque' || response.ok };
} catch { return { provider, ok: false }; }
finally { clearTimeout(timer); }
}));
label.textContent = results.some(r => r.ok) ? 'Este aparelho alcançou um serviço externo. Você pode abrir o aplicativo do banco.' : 'A sessão está ativa, mas não foi possível confirmar o acesso externo. Verifique se o aplicativo do banco abre.';
try { await fetch('/api/access/report', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ mac, token, results }) }); } catch { /* report is optional */ }
}
async function loadSiteConfig() {
try {
const res = await fetch('/api/config');
const d = await res.json();
if (Number.isInteger(d.freeSeconds) && d.freeSeconds > 0) freeSeconds = d.freeSeconds;
if (Number.isInteger(d.freeCooldownSeconds) && d.freeCooldownSeconds >= 2700) freeCooldownSeconds = d.freeCooldownSeconds;
renderAccessRules();
if (typeof d.privacy?.controller === 'string' && d.privacy.controller.trim()) $('privacyController').textContent = d.privacy.controller;
if (typeof d.privacy?.contact === 'string' && d.privacy.contact.trim()) $('privacyContact').textContent = d.privacy.contact;
if (typeof d.privacy?.retention === 'string' && d.privacy.retention.trim()) $('privacyRetention').textContent = d.privacy.retention;
if (d.ssid) $('ssidLabel').textContent = d.ssid;
if (/^(?:\d{1,3}\.){3}\d{1,3}$/.test(d.hotspotIp)) HS_LOGIN = 'http://' + d.hotspotIp + '/login';
$('wifiEntry').href = HS_LOGIN;
} catch { /* usa padrao */ }
}
loadSiteConfig().then(startFreeAccess);
loadSiteConfig().then(() => {
const pendingPix = sessionStorage.getItem('pendingPix');
const returningFromAccess = new URLSearchParams(location.search).get('free') === '1' &&
(!pendingPix || Number(sessionStorage.getItem('freeAccessConfirmedUntil') || 0) > Date.now() ||
Number(sessionStorage.getItem('freeLoginAttemptUntil') || 0) > Date.now());
if (!/^([0-9a-f]{2}:){5}[0-9a-f]{2}$/i.test(mac) || returningFromAccess) startFreeAccess();
else {
$('freeAccessMessage').textContent = pendingPix ? 'Seu PIX está aqui. Toque em “Copiar código PIX” e siga os passos.' : 'Vamos começar? Escolha um plano abaixo.';
}
});
show('plans');
loadPlans();
if (sessionStorage.getItem('paymentId')) {
currentPaymentId = sessionStorage.getItem('paymentId');
try {
const pending = JSON.parse(sessionStorage.getItem('pendingPix') || 'null');
if (pending?.paymentId === currentPaymentId) {
$('payTitle').textContent = pending.planName + ' · ' + money(pending.price);
$('qrImg').src = pending.qrCodeBase64 ? 'data:image/png;base64,' + pending.qrCodeBase64 : '';
$('copiaCola').textContent = pending.copiaCola || '';
show('pay');
pollTimer = setInterval(verify, 6000);
}
} catch { sessionStorage.removeItem('pendingPix'); }
verify();
}
</script>
+6 -1
View File
@@ -17,11 +17,16 @@ const config = {
},
port: parseInt(process.env.PORT || '3000', 10),
freeAccessSeconds: Number(process.env.FREE_ACCESS_SECONDS || 120),
freeAccessCooldownSeconds: Number(process.env.FREE_ACCESS_COOLDOWN_SECONDS || 300),
freeAccessCooldownSeconds: Math.max(2700, Number(process.env.FREE_ACCESS_COOLDOWN_SECONDS || 2700)),
ssidName: process.env.SSID_NAME || 'Internet Gratis',
hotspotIp: process.env.HOTSPOT_IP || '10.10.10.1',
baseUrl: process.env.BASE_URL || 'http://192.168.3.100:3000',
adminToken: process.env.ADMIN_TOKEN || '',
privacy: {
controller: process.env.LGPD_RESPONSAVEL || '',
contact: process.env.LGPD_CONTATO || '',
retention: process.env.LGPD_RETENCAO || '',
},
dataDir: process.env.DATA_DIR || path.join(__dirname, '..', 'data'),
};
+32 -10
View File
@@ -2,7 +2,7 @@ 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 { rateLimit, validMac, validatePlans, equalSecret } from './security.js';
import { safeAsyncRoutes } from './http.js';
import { verifyWebhook } from './webhook.js';
import path from 'node:path';
@@ -10,7 +10,7 @@ import { fileURLToPath } from 'node:url';
import config from './config.js';
import { initDb, getDb, saveDb, genCode } from './db.js';
import { initMp, createPixPayment, getPaymentStatus, cancelOrder, validCpf } from './mp.js';
import { rosCommand, createHotspotUser, allowPaymentAccess, revokePaymentAccess, paymentAccessStatus, loginPaymentAccess } from './ros.js';
import { rosCommand, createHotspotUser, allowPaymentAccess, revokePaymentAccess, paymentAccessStatus, loginPaymentAccess, activatePaidAccess } from './ros.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export const app = express();
@@ -36,12 +36,13 @@ initDb();
saveDb();
initMp();
const { checkPayment, checks } = paymentService({ getDb, saveDb, getPaymentStatus, rosCommand, createHotspotUser });
const { checkPayment, checks } = paymentService({ getDb, saveDb, getPaymentStatus, rosCommand, createHotspotUser, activatePaidAccess });
// ===== Rotas =====
// ===== Internet temporaria para pagar (bypass do hotspot) =====
const accessLocks = new Set();
const accessRetryAt = t => Math.max(t.cooldownUntil || 0, Date.parse(t.createdAt) + (config.freeAccessSeconds + config.freeAccessCooldownSeconds) * 1000);
app.post('/api/access/start', async (req, res) => {
const mac = typeof req.body?.mac === 'string' ? req.body.mac.toUpperCase() : '';
if (!validMac(mac)) return res.status(400).json({ error: 'mac obrigatorio' });
@@ -53,13 +54,14 @@ app.post('/api/access/start', async (req, res) => {
const prev = (db.tempAccess || []).find((t) => t.mac === mac);
// reusa a janela criada ha menos de X minutos (evita abuso de janelas ilimitadas)
if (prev && now - Date.parse(prev.createdAt) < config.freeAccessCooldownSeconds * 1000) {
if (prev.expiresAt <= now || prev.revoked) return res.status(429).json({ error: 'O acesso temporário terminou. Aguarde para solicitar novamente.', retryAfterSeconds: Math.ceil((Date.parse(prev.createdAt) + config.freeAccessCooldownSeconds * 1000 - now) / 1000) });
if (prev && now < accessRetryAt(prev)) {
if (prev.expiresAt <= now || prev.revoked) return res.status(429).json({ error: 'O acesso temporário terminou. Aguarde para solicitar novamente.', retryAfterSeconds: Math.ceil((accessRetryAt(prev) - now) / 1000) });
const previousUrl = new URL(prev.loginUrl);
if (!prev.probeToken) { prev.probeToken = crypto.randomBytes(24).toString('hex'); saveDb(); }
let authenticated = false;
try { authenticated = await loginPaymentAccess({ mac, user: prev.user, pass: previousUrl.searchParams.get('password') }); }
catch (e) { console.error('[ACESSO LOGIN]', e.message); }
return res.json({ ok: true, seconds: Math.max(0, Math.ceil((prev.expiresAt - Date.now()) / 1000)), expiresAt: prev.expiresAt, authenticated, loginUrl: prev.loginUrl, reused: true });
return res.json({ ok: true, seconds: Math.max(0, Math.ceil((prev.expiresAt - Date.now()) / 1000)), expiresAt: prev.expiresAt, probeToken: prev.probeToken, authenticated, loginUrl: prev.loginUrl, reused: true });
}
const r = await allowPaymentAccess(mac, config.freeAccessSeconds);
@@ -79,6 +81,8 @@ app.post('/api/access/start', async (req, res) => {
loginUrl,
createdAt: new Date(startedAt).toISOString(),
expiresAt: startedAt + config.freeAccessSeconds * 1000,
cooldownUntil: startedAt + (config.freeAccessSeconds + config.freeAccessCooldownSeconds) * 1000,
probeToken: crypto.randomBytes(24).toString('hex'),
});
saveDb();
@@ -86,7 +90,7 @@ app.post('/api/access/start', async (req, res) => {
try { authenticated = await loginPaymentAccess(r); }
catch (e) { console.error('[ACESSO LOGIN]', e.message); }
const expiresAt = startedAt + config.freeAccessSeconds * 1000;
res.json({ ok: true, seconds: Math.max(0, Math.ceil((expiresAt - Date.now()) / 1000)), expiresAt, authenticated, loginUrl, user: r.user });
res.json({ ok: true, seconds: Math.max(0, Math.ceil((expiresAt - Date.now()) / 1000)), expiresAt, probeToken: db.tempAccess.find(t => t.mac === mac).probeToken, authenticated, loginUrl, user: r.user });
} catch (e) {
console.error('[ACESSO]', e.message);
res.status(500).json({ error: 'Falha na operação. Consulte os logs do servidor.' });
@@ -95,6 +99,23 @@ app.post('/api/access/start', async (req, res) => {
}
});
// Diagnostic reports never grant or extend network access. They are observations
// made by the guest browser, not a claim about which radio interface it used.
app.post('/api/access/report', rateLimit(20, 60000), (req, res) => {
const { mac, token, results } = req.body || {};
if (!validMac(mac) || !Array.isArray(results) || results.length !== 2 ||
new Set(results.map(r => r?.provider)).size !== 2 || results.some(r => !r || !['google', 'apple'].includes(r.provider) || typeof r.ok !== 'boolean')) {
return res.status(400).json({ error: 'Relatório inválido' });
}
const record = (getDb().tempAccess || []).find(t => t.mac === mac.toUpperCase());
if (!record || !equalSecret(token, record.probeToken)) return res.sendStatus(403);
if (record.revoked || record.expiresAt <= Date.now()) return res.sendStatus(410);
record.clientProbe = { at: new Date().toISOString(), source: 'guest-browser', results: results.map(r => ({ provider: r.provider, ok: r.ok })) };
saveDb();
console.log('[ACESSO CLIENTE]', crypto.createHash('sha256').update(record.mac).digest('hex').slice(0, 10), results.some(r => r.ok) ? 'external-reply' : 'external-unconfirmed');
res.json({ ok: true });
});
app.get('/api/access/status/:mac', adminAuth, async (req, res) => {
try {
res.json(await paymentAccessStatus(req.params.mac));
@@ -114,7 +135,7 @@ app.post('/api/reconcile', adminAuth, async (req, res) => {
});
app.get('/api/config', (req, res) => {
res.json({ ssid: config.ssidName, freeSeconds: config.freeAccessSeconds, hotspotIp: config.hotspotIp });
res.json({ ssid: config.ssidName, freeSeconds: config.freeAccessSeconds, freeCooldownSeconds: config.freeAccessCooldownSeconds, hotspotIp: config.hotspotIp, privacy: config.privacy });
});
app.get('/api/plans', (req, res) => {
@@ -205,6 +226,7 @@ app.get('/api/status/:id', async (req, res) => {
status: payment.status,
orderId: payment.mpId,
voucher: payment.voucher,
connection: payment.connection,
planName: getDb().plans.find((p) => p.id === payment.planId)?.name,
});
});
@@ -254,7 +276,7 @@ let polling = false;
setInterval(async () => {
if (polling) return;
polling = true;
try { for (const p of getDb().payments.filter(p => p.status === 'pending' && p.mpId)) await checkPayment(p); }
try { for (const p of getDb().payments.filter(p => p.mpId && (p.status === 'pending' || p.status === 'paid' && p.connection?.state === 'pending'))) await checkPayment(p); }
finally { polling = false; }
}, 15000).unref();
let cleaning = false;
@@ -269,7 +291,7 @@ setInterval(async () => {
catch (e) { console.error('[ACESSO]', e.message); }
}
}
db.tempAccess = (db.tempAccess || []).filter(t => !t.revoked || Date.parse(t.createdAt) + config.freeAccessCooldownSeconds * 1000 > Date.now());
db.tempAccess = (db.tempAccess || []).filter(t => !t.revoked || accessRetryAt(t) > Date.now());
saveDb();
} catch (e) { console.error('[LIMPEZA]', e.message); } finally { cleaning = false; }
}, 15000).unref();
+18 -7
View File
@@ -1,8 +1,22 @@
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 }) {
export function paymentService({ getDb, saveDb, getPaymentStatus, rosCommand, createHotspotUser, activatePaidAccess }) {
const checks = new Map();
async function connect(payment) {
if (!payment.mac || !payment.voucher || !activatePaidAccess || payment.connection?.state === 'active') return payment;
payment.connection = { state: 'pending' };
saveDb();
try {
if (await activatePaidAccess(payment)) {
payment.connection = { state: 'active', connectedAt: new Date().toISOString() };
const temp = (getDb().tempAccess || []).find(t => t.mac === payment.mac);
if (temp) temp.expiresAt = Date.now();
saveDb();
}
} catch (e) { console.error('[PAGAMENTO CONEXAO]', e.message); }
return payment;
}
async function fulfill(payment) {
if (payment.voucher) return payment;
if (!payment.uptime) throw new Error('Pagamento sem limite de uso');
@@ -20,18 +34,15 @@ export function paymentService({ getDb, saveDb, getPaymentStatus, rosCommand, cr
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;
return connect(payment);
}
async function checkPayment(payment) {
if (!payment.mpId || payment.status !== 'pending') return payment;
if (!payment.mpId || !['pending', 'paid'].includes(payment.status)) return payment;
if (checks.has(payment.id)) return checks.get(payment.id);
const task = (async () => {
try {
if (payment.status === 'paid') return await connect(payment);
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(); }
+20
View File
@@ -236,6 +236,26 @@ export async function loginPaymentAccess({ mac, user, pass }) {
return temporaryAccessActive(mac);
}
// Promote the same connected device to its paid voucher without a browser login.
export async function activatePaidAccess(payment) {
const { mac, voucher } = payment;
if (!mac || !voucher) return false;
const sessions = await rosCommand(['/ip/hotspot/active/print', `?mac-address=${mac}`]);
const own = sessions.filter(row => pickField(row, '=server=') === config.mikrotik.server);
if (own.some(row => pickField(row, '=user=') === voucher.user)) return true;
// Never disconnect a different paid account or another hotspot server.
if (sessions.some(row => pickField(row, '=user=') !== freeUserName(mac) || pickField(row, '=server=') !== config.mikrotik.server)) return false;
const ip = own.map(row => pickField(row, '=address=')).find(Boolean) || await hostAddressByMac(mac);
if (!ip) return false;
for (const row of own) {
const id = pickField(row, '=.id=');
if (id) await rosCommand(['/ip/hotspot/active/remove', `=numbers=${id}`]);
}
await rosCommand(['/ip/hotspot/active/login', `=user=${voucher.user}`, `=password=${voucher.pass}`, `=ip=${ip}`, `=mac-address=${mac}`]);
const active = await rosCommand(['/ip/hotspot/active/print', `?mac-address=${mac}`]);
return active.some(row => pickField(row, '=user=') === voucher.user && pickField(row, '=server=') === config.mikrotik.server);
}
function pickField(row, key) {
const v = (row || []).find((w) => w.startsWith(key));
return v ? v.slice(key.length) : null;
+20 -1
View File
@@ -52,6 +52,7 @@ test('admin API authenticates, creates, lists, blocks, disconnects and exports w
});
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);
process.env.FREE_ACCESS_COOLDOWN_SECONDS='300'; // Existing ZimaOS installations must also enforce 45 minutes.
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');
@@ -60,6 +61,7 @@ test('admin API authenticates, creates, lists, blocks, disconnects and exports w
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');
assert.equal(config.freeAccessCooldownSeconds,2700);
const originalToken = config.adminToken;
config.adminToken = 'replace-with-at-least-32-random-characters';
assert.equal((await request('/api/admin/users')).status,503);
@@ -78,15 +80,32 @@ test('admin API authenticates, creates, lists, blocks, disconnects and exports w
// Temporary access is confirmed by RouterOS, bounded in seconds, and reused.
res=await request('/api/access/start','POST',{mac:'aa:bb:cc:dd:ee:11'});assert.equal(res.status,200);
const temporary=await res.json();assert.equal(temporary.authenticated,true);assert.ok(temporary.seconds>0 && temporary.seconds<=120);
assert.ok(temporary.probeToken);
const probeResults=[{provider:'google',ok:true},{provider:'apple',ok:false}];
assert.equal((await request('/api/access/report','POST',{mac:'AA:BB:CC:DD:EE:11',token:'wrong',results:probeResults})).status,403);
assert.equal((await request('/api/access/report','POST',{mac:'AA:BB:CC:DD:EE:11',token:temporary.probeToken,results:probeResults})).status,200);
const free=users.find(u=>u.name==='FREEAABBCCDDEE11');assert.equal(free['limit-uptime'],'120s');assert.equal(free['mac-address'],'AA:BB:CC:DD:EE:11');
assert.equal(profiles.find(p=>p.name==='pix-free')['session-timeout'],'120s');
const loginCount=commands.filter(c=>c[0]==='/ip/hotspot/active/login').length;
res=await request('/api/access/start','POST',{mac:'AA:BB:CC:DD:EE:11'});assert.equal((await res.json()).authenticated,true);
assert.equal(commands.filter(c=>c[0]==='/ip/hotspot/active/login').length,loginCount);
const {getDb}=await import('../src/db.js');getDb().tempAccess.find(t=>t.mac==='AA:BB:CC:DD:EE:11').expiresAt=Date.now()-1;
assert.equal((await request('/api/access/start','POST',{mac:'AA:BB:CC:DD:EE:11'})).status,429);
assert.equal((await request('/api/access/report','POST',{mac:'AA:BB:CC:DD:EE:11',token:temporary.probeToken,results:probeResults})).status,410);
const cooldownResponse=await request('/api/access/start','POST',{mac:'AA:BB:CC:DD:EE:11'});
assert.equal(cooldownResponse.status,429);
assert.ok((await cooldownResponse.json()).retryAfterSeconds>=2700);
denyLogin=true;res=await request('/api/access/start','POST',{mac:'AA:BB:CC:DD:EE:22'});const fallback=await res.json();assert.equal(fallback.authenticated,false);assert.ok(fallback.loginUrl);
denyLogin=false;
const {activatePaidAccess}=await import('../src/ros.js');
const paid={mac:'AA:BB:CC:DD:EE:11',voucher:{user:'purchased-voucher',pass:'paid-password'}};
assert.equal(await activatePaidAccess(paid),true);
assert.ok(active.some(a=>a.user==='purchased-voucher'));
assert.ok(!active.some(a=>a.user==='FREEAABBCCDDEE11'));
const paidLoginCount=commands.filter(c=>c[0]==='/ip/hotspot/active/login').length;
assert.equal(await activatePaidAccess(paid),true);
assert.equal(commands.filter(c=>c[0]==='/ip/hotspot/active/login').length,paidLoginCount);
assert.equal(await activatePaidAccess({...paid,voucher:{user:'different-paid-account',pass:'other'}}),false);
assert.ok(active.some(a=>a.user==='purchased-voucher'));
active.push({'.id':'*F',user:'paid-voucher',server:'guest-hotspot','mac-address':'AA:BB:CC:DD:EE:11'});
const {revokePaymentAccess}=await import('../src/ros.js');await revokePaymentAccess('AA:BB:CC:DD:EE:11');assert.ok(active.some(a=>a.user==='paid-voucher'));assert.ok(!active.some(a=>a.user==='FREEAABBCCDDEE11'));
trap=true;res=await request('/api/admin/users');assert.equal(res.status,500);assert.ok(!(await res.text()).includes('simulated failure'));
+207
View File
@@ -0,0 +1,207 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import vm from 'node:vm';
const html=fs.readFileSync(new URL('../public/index.html',import.meta.url),'utf8');
const code=html.match(/<script>([\s\S]*?)<\/script>/)[1];
async function portal({search,storage={},access={ok:true,authenticated:true,seconds:120},externalAvailable=true,clipboardAvailable=true,legacyCopy=false,siteConfig={},paymentStatus={status:'pending'}}) {
const ids=[...html.matchAll(/\bid="([^"]+)"/g)].map(m=>m[1]);
const listeners=new Map(),clipboard=[];
const elements=new Map(ids.map(id=>[id,{textContent:'',hidden:false,disabled:false,value:'',innerHTML:'',style:{},attributes:{},setAttribute(k,v){this.attributes[k]=v;},removeAttribute(k){delete this.attributes[k];},classList:{toggle(){},add(){},remove(){}},addEventListener:(event,fn)=>listeners.set(id+':'+event,fn),appendChild(){}}]));
const requests=[],forms=[],intervals=[],navigations=[];
const sandbox={URL,URLSearchParams,Date,AbortController,console,location:{search},navigator:{},sessionStorage:{getItem:k=>storage[k]??null,setItem:(k,v)=>storage[k]=v,removeItem:k=>delete storage[k]},document:{getElementById:id=>{assert.ok(elements.has(id),'Missing element '+id);return elements.get(id);},body:{append(){}},createElement:tag=>({append(){},submit(){forms.push(tag);}})},setTimeout(){},clearTimeout(){},setInterval:fn=>{intervals.push(fn);return intervals.length;},clearInterval(){},window:{addEventListener(){},scrollTo(){}}};
sandbox.location.href='https://hotspot.example.test/'+(search || '');
sandbox.window.location={replace:url=>navigations.push(url)};
sandbox.navigator.clipboard={writeText:async text=>{if(!clipboardAvailable)throw new Error('Clipboard denied');clipboard.push(text);}};
sandbox.document.body.appendChild=()=>{};
sandbox.document.createElement=tag=>({append(){},select(){},remove(){},submit(){forms.push(tag);}});
sandbox.document.execCommand=()=>legacyCopy;
sandbox.fetch=async(path,options)=>{
requests.push({path,options});
if(path==='/api/config')return {ok:true,json:async()=>({hotspotIp:'10.10.10.1',ssid:'Test',...siteConfig})};
if(path==='/api/plans')return {ok:true,json:async()=>[]};
if(path==='/api/access/start')return {ok:access.ok,status:access.ok?200:429,json:async()=>access};
if(path==='/api/checkout')return {ok:true,json:async()=>({paymentId:'Ptest',orderId:'ORDtest',price:3,planName:'1 Hora',copiaCola:'test-pix',qrCodeBase64:null})};
if(path==='/api/status/Ptest')return {ok:true,json:async()=>paymentStatus};
if(path==='/api/access/report')return {ok:true,json:async()=>({ok:true})};
if(path.startsWith('https://www.gstatic.com/') || path.startsWith('https://www.apple.com/')) {
// Fetch rejects no-cors requests unless redirect mode is follow, before any network traffic.
if(options.mode==='no-cors' && (options.redirect ?? 'follow')!=='follow')throw new TypeError('Invalid no-cors redirect mode');
if(!externalAvailable)throw new Error('Network unreachable');
return {type:'opaque',ok:false};
}
throw new Error('Unexpected request '+path);
};
vm.runInNewContext(code,sandbox);
for(let i=0;i<10;i++)await new Promise(r=>setImmediate(r));
return {requests,elements,forms,intervals,navigations,clipboard,click:async id=>{
await listeners.get(id+':click')();
for(let i=0;i<10;i++)await new Promise(r=>setImmediate(r));
},checkout:async()=>{
elements.get('payerName').value='Teste Usuario';elements.get('payerEmail').value='[email protected]';
await vm.runInNewContext('checkout("plano-1h")',sandbox);
for(let i=0;i<10;i++)await new Promise(r=>setImmediate(r));
}};
}
test('return from hotspot confirms session even with stale freeOk/freeTried browser flags',async()=>{
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11&free=1',storage:{freeOk:'1',freeTried:'1'}});
const request=p.requests.find(r=>r.path==='/api/access/start');assert.ok(request);
assert.equal(JSON.parse(request.options.body).mac,'AA:BB:CC:DD:EE:11');
assert.match(p.elements.get('freeAccessMessage').textContent,/confirmada: 120 segundos/);
assert.equal(p.forms.length,0);
});
test('direct portal URL without MAC cannot silently claim temporary access',async()=>{
const p=await portal({search:''});
assert.equal(p.requests.filter(r=>r.path==='/api/access/start').length,0);
assert.match(p.elements.get('freeAccessMessage').textContent,/tela de entrada/);
});
test('portal reports cooldown failures and offers retry',async()=>{
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11&free=1',access:{ok:false,error:'Janela encerrada.',retryAfterSeconds:180}});
assert.match(p.elements.get('freeAccessMessage').textContent,/3 minutos/);
assert.ok(p.elements.has('copyBtn'));
});
test('browsing plans does not consume the payment internet window',async()=>{
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11'});
assert.equal(p.requests.filter(r=>r.path==='/api/access/start').length,0);
assert.match(p.elements.get('freeAccessMessage').textContent,/Escolha um plano/);
});
test('generating or restoring a PIX leaves it visible without granting internet or navigating',async()=>{
const storage={};
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11',storage});
await p.checkout();
const paths=p.requests.map(r=>r.path);
assert.ok(paths.includes('/api/checkout'));
assert.ok(!paths.includes('/api/access/start'));
assert.equal(p.navigations.length,0);
assert.match(p.elements.get('freeAccessMessage').textContent,/Copiar código PIX/);
assert.equal(JSON.parse(storage.pendingPix).paymentId,'Ptest');
assert.equal(p.elements.get('copiaCola').textContent,'test-pix');
const reloaded=await portal({search:'?mac=AA:BB:CC:DD:EE:11',storage});
assert.equal(reloaded.elements.get('copiaCola').textContent,'test-pix');
assert.ok(reloaded.requests.some(r=>r.path==='/api/status/Ptest'));
assert.ok(!reloaded.requests.some(r=>r.path==='/api/access/start'));
const staleReturn=await portal({search:'?mac=AA:BB:CC:DD:EE:11&free=1',storage});
assert.ok(!staleReturn.requests.some(r=>r.path==='/api/access/start'));
});
test('client probes external services and reports observations without sending its token externally',async()=>{
for(const externalAvailable of [true,false]){
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11&free=1',access:{ok:true,authenticated:true,seconds:120,probeToken:'secret-probe'},externalAvailable});
const report=p.requests.find(r=>r.path==='/api/access/report');assert.ok(report);
assert.equal(JSON.parse(report.options.body).results.every(r=>r.ok),externalAvailable);
const external=p.requests.filter(r=>r.path.startsWith('https:'));assert.equal(external.length,2);
for(const r of external){
assert.ok(!JSON.stringify(r).includes('secret-probe'));
assert.equal(r.options.mode,'no-cors');
assert.equal(r.options.redirect,'follow');
assert.equal(r.options.credentials,'omit');
}
assert.match(p.elements.get('freeAccessProbe').textContent,externalAvailable?/alcançou/:/não foi possível confirmar/);
}
});
test('unsupported API login falls back to the hotspot form without claiming confirmed access',async()=>{
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11&free=1',access:{ok:true,authenticated:false,seconds:120,loginUrl:'http://10.10.10.1/login?username=FREE&password=test&dst=https%3A%2F%2Fhotspot.jf.eng.br%2F'}});
assert.equal(p.forms.length,1);
assert.match(p.elements.get('freeAccessMessage').textContent,/ainda não confirmou/);
assert.equal(p.requests.filter(r=>r.path==='/api/access/report').length,0);
});
test('API login navigates once to trigger captive-network revalidation and restores the PIX',async()=>{
const storage={};
const expiresAt=Date.now()+120000;
const access={ok:true,authenticated:true,seconds:120,expiresAt,probeToken:'private-probe'};
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11',storage,access});
await p.checkout();
assert.equal(p.navigations.length,0);
assert.equal(p.requests.filter(r=>r.path==='/api/access/start').length,0);
await p.click('copyBtn');
assert.deepEqual(p.clipboard,['test-pix']);
assert.equal(p.navigations.length,1);
const target=new URL(p.navigations[0]);
assert.equal(target.origin,'https://hotspot.example.test');
assert.equal(target.searchParams.get('mac'),'AA:BB:CC:DD:EE:11');
assert.equal(target.searchParams.get('free'),'1');
assert.equal(target.searchParams.get('access'),String(expiresAt));
assert.ok(!target.href.includes('private-probe'));
assert.equal(JSON.parse(storage.pendingPix).paymentId,'Ptest');
assert.equal(p.requests.filter(r=>r.path==='/api/access/report').length,0);
const back=await portal({search:target.search,storage,access:{...access,seconds:103,reused:true}});
assert.equal(back.navigations.length,0);
assert.equal(back.elements.get('copiaCola').textContent,'test-pix');
assert.match(back.elements.get('freeAccessMessage').textContent,/103 segundos/);
assert.ok(back.requests.some(r=>r.path==='/api/access/report'));
assert.equal(storage.freeAccessConfirmedUntil,String(expiresAt));
});
test('failed clipboard copy keeps the PIX open without consuming the internet window',async()=>{
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11',clipboardAvailable:false});
await p.checkout();
await p.click('copyBtn');
assert.equal(p.requests.filter(r=>r.path==='/api/access/start').length,0);
assert.equal(p.navigations.length,0);
assert.equal(p.elements.get('copyBtn').disabled,false);
assert.match(p.elements.get('toast').textContent,/copie o código manualmente/);
assert.equal(p.elements.has('retryFreeAccess'),false);
await p.click('copyBtn');
assert.equal(p.requests.filter(r=>r.path==='/api/access/start').length,0);
});
test('legacy clipboard success permits access only after the copy attempt succeeds',async()=>{
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11',clipboardAvailable:false,legacyCopy:true});
await p.checkout();
await p.click('copyBtn');
assert.equal(p.requests.filter(r=>r.path==='/api/access/start').length,1);
});
test('an expired or denied window cannot navigate, and a new window can revalidate again',async()=>{
const previous=Date.now()-1000;
const storage={freeAccessConfirmedUntil:String(previous)};
const search='?mac=AA:BB:CC:DD:EE:11&free=1';
const expired=await portal({search,storage,access:{ok:true,authenticated:true,seconds:0,expiresAt:previous}});
assert.equal(expired.navigations.length,0);
const denied=await portal({search,storage,access:{ok:false,error:'Aguarde',expiresAt:Date.now()+120000}});
assert.equal(denied.navigations.length,0);
const next=await portal({search,storage,access:{ok:true,authenticated:true,seconds:120,expiresAt:Date.now()+120000}});
assert.equal(next.navigations.length,1);
});
test('guided payment has clear rules and one copy action without a separate release button',async()=>{
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11',siteConfig:{freeSeconds:180,freeCooldownSeconds:2700}});
assert.match(p.elements.get('accessRules').textContent,/3 minutos/);
assert.match(p.elements.get('accessRules').textContent,/45 minutos após o fim/);
assert.equal(p.elements.has('retryFreeAccess'),false);
assert.equal(p.elements.has('accessConsent'),false);
await p.checkout();
assert.equal(p.elements.get('step-pay').attributes['aria-current'],'step');
assert.equal(p.requests.filter(r=>r.path==='/api/access/start').length,0);
await p.click('copyBtn');
assert.equal(p.requests.filter(r=>r.path==='/api/access/start').length,1);
});
test('privacy information is available outside the steps and never requests a bank password',()=>{
assert.match(html,/<details[^>]*id="privacyNotice"/);
assert.match(html,/Seus dados e sua privacidade \(LGPD\)/);
assert.match(html,/não pede sua senha do banco/);
assert.match(html,/acesso, correção e exclusão quando cabível/);
assert.ok(!html.includes('id="retryFreeAccess"'));
});
test('privacy environment fields render as text, including markup, without replacing HTML',async()=>{
const privacy={controller:'Empresa Exemplo',contact:'[email protected]',retention:'Registros de compra: <b>prazo definido pelo responsável</b>'};
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11',siteConfig:{privacy}});
assert.equal(p.elements.get('privacyController').textContent,privacy.controller);
assert.equal(p.elements.get('privacyContact').textContent,privacy.contact);
assert.equal(p.elements.get('privacyRetention').textContent,privacy.retention);
assert.equal(p.elements.get('privacyRetention').innerHTML,'');
assert.equal(p.requests.filter(r=>r.path==='/api/access/start').length,0);
});
test('confirmed payment distinguishes activation pending from an active paid connection',async()=>{
for(const state of ['pending','active']){
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11',storage:{paymentId:'Ptest'},paymentStatus:{status:'paid',voucher:{user:'paid-user',pass:'paid-pass'},connection:{state}}});
assert.equal(p.elements.get('vUser').textContent,'paid-user');
assert.match(p.elements.get('paidConnectionMessage').textContent,state==='active'?/plano está ativo/:/Ativando/);
assert.equal(p.elements.get('freeCountdown').textContent,state==='active'?'Conectado':'Ativando');
assert.equal(p.forms.length,0);
}
});
+21
View File
@@ -54,3 +54,24 @@ test('unconfirmed payments never provision users', async () => {
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');
});
test('paid handoff retries without another charge or voucher and preserves temporary access until connected',async()=>{
const temp={mac:'AA:BB:CC:DD:EE:11',expiresAt:Date.now()+120000};
const originalExpiry=temp.expiresAt;
const p={id:'P4',mpId:'ORD4',status:'pending',profile:'pix-1h',uptime:'1h',mac:temp.mac};
let queries=0,creates=0,attempts=0;
const svc=paymentService({getDb:()=>({tempAccess:[temp]}),saveDb:()=>{},getPaymentStatus:async()=>{queries++;return 'approved';},rosCommand:async()=>[],createHotspotUser:async()=>{creates++;},activatePaidAccess:async payment=>{
assert.equal(payment.status,'paid');assert.ok(payment.voucher);
if(++attempts===1)throw new Error('Router temporarily unavailable');
return true;
}});
await svc.checkPayment(p);
assert.equal(p.status,'paid');assert.equal(p.connection.state,'pending');
assert.equal(temp.expiresAt,originalExpiry);
const voucher=p.voucher;
await Promise.all([svc.checkPayment(p),svc.checkPayment(p)]);
assert.equal(p.connection.state,'active');assert.equal(p.voucher,voucher);
assert.ok(temp.expiresAt<=Date.now());assert.equal(queries,1);assert.equal(creates,1);
const completedAttempts=attempts;
await svc.checkPayment(p);assert.equal(attempts,completedAttempts);
});
+4 -1
View File
@@ -36,4 +36,7 @@ services:
TRUST_PROXY: "${TRUST_PROXY:-}"
HOTSPOT_IP: "10.10.10.1"
FREE_ACCESS_SECONDS: "120"
FREE_ACCESS_COOLDOWN_SECONDS: "300"
FREE_ACCESS_COOLDOWN_SECONDS: "2700"
LGPD_RESPONSAVEL: "${LGPD_RESPONSAVEL:-}"
LGPD_CONTATO: "${LGPD_CONTATO:-}"
LGPD_RETENCAO: "${LGPD_RETENCAO:-}"
+12
View File
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="refresh" content="0;url=$(link-redirect)">
<title>INCTG — Acesso autorizado</title>
</head>
<body>
<p>Acesso autorizado. <a href="$(link-redirect)">Continuar para o portal</a>.</p>
</body>
</html>
+3 -2
View File
@@ -3,6 +3,7 @@
:local guestSubnet "10.10.10.0/24"
:local guestIP "10.10.10.1"
:local backendIP "192.168.3.100"
:local backendPort 3000
:local portalHost "hotspot.jf.eng.br"
:local wanInterface "ether1"
:local guestInterface "ether4"
@@ -37,7 +38,7 @@
# Private-network guard runs before existing accepts/fasttrack.
# Internet returns to the ordinary chain so HotSpot filtering still applies.
/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=$backendIP protocol=tcp dst-port=$backendPort 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
@@ -51,7 +52,7 @@
# Restrict pre-login exception to the portal host, not all Cloudflare IPs.
/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"
/ip hotspot walled-garden ip add dst-address=$backendIP dst-port=$backendPort protocol=tcp action=accept comment="pix: local portal"
# HotSpot is IPv4-only: prevent an IPv6 path around authentication.
:do {
/ipv6 firewall filter add chain=forward in-interface=bridge-guest action=drop place-before=0 comment="pix: block guest IPv6"