Copy PIX successfully before granting internet and closing captive portal
build-image / build-push (push) Successful in 2m47s

This commit is contained in:
jfeng committed 2026-10-22 17:37:38 +00:00
1 parent 8d38a9136b
commit b69b3afa5d
3 files changed
+76 -20

No files matched your search

+2 -2
View File
@@ -5,8 +5,8 @@ Portal de venda de acesso Wi-Fi integrado ao Mercado Pago (Orders API) e ao hots
## Fluxo ## Fluxo
1. O MikroTik redireciona o convidado para o portal, com `?mac=...`. 1. O MikroTik redireciona o convidado para o portal, com `?mac=...`.
2. Depois de gerar o PIX, o backend cria uma conta temporária vinculada ao MAC e tenta autenticar o dispositivo pela API `/ip/hotspot/active/login`. O convidado também pode iniciar essa janela pelo botão de liberação. O sistema 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]`. Apenas navegar pelos planos não consome a janela. 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. O comprador escolhe o plano, informa nome/e-mail e gera o PIX. 3. Ao tocar em **Copiar PIX e liberar internet**, o portal confirma a cópia antes de solicitar ao backend a conta temporária vinculada ao MAC e autenticar pela API `/ip/hotspot/active/login` (120 segundos; intervalo mínimo de 300 segundos). Se a cópia falhar, mantém a tela aberta e orienta copiar manualmente; o botão **Já copiei: liberar internet** permite continuar após a cópia manual ou leitura do QR Code. A janela de entrada do Wi-Fi pode fechar quando o aparelho reconhece a internet: nesse momento, o código já está copiado para colar no banco. Se o login pela API não estiver disponível, tenta a tela do hotspot; falhas ficam visíveis no portal e nos logs `[ACESSO]`/`[ACESSO LOGIN]`. Apenas gerar ou restaurar um PIX não consome a janela.
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. 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. 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. 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.
+30 -11
View File
@@ -533,7 +533,7 @@
<section id="view-pay" class="card hidden" aria-labelledby="payTitle"> <section id="view-pay" class="card hidden" aria-labelledby="payTitle">
<div class="pay-head"> <div class="pay-head">
<h2 id="payTitle">PIX</h2> <h2 id="payTitle">PIX</h2>
<p>Escaneie o QR Code no app do seu banco</p> <p>Copie o PIX antes de abrir o banco. Ao liberar a internet, esta janela pode fechar automaticamente.</p>
</div> </div>
<div class="qr-panel"> <div class="qr-panel">
@@ -543,7 +543,7 @@
<div class="copia" id="copiaCola" title="Código copia e cola"></div> <div class="copia" id="copiaCola" title="Código copia e cola"></div>
<div class="row"> <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 PIX e liberar internet</button>
<button class="btn btn-primary" id="checkBtn" type="button">Já paguei</button> <button class="btn btn-primary" id="checkBtn" type="button">Já paguei</button>
</div> </div>
@@ -641,16 +641,20 @@
async function copy(text, msg) { async function copy(text, msg) {
try { try {
await navigator.clipboard.writeText(text); await navigator.clipboard.writeText(text);
toast(msg || 'Copiado!');
} catch { } catch {
const ta = document.createElement('textarea'); const ta = document.createElement('textarea');
ta.value = text; ta.value = text;
document.body.appendChild(ta); document.body.appendChild(ta);
ta.select(); ta.select();
document.execCommand('copy'); try {
ta.remove(); if (!document.execCommand('copy')) throw new Error('Clipboard unavailable');
toast(msg || 'Copiado!'); } 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) { function show(view) {
@@ -724,7 +728,9 @@
clearInterval(pollTimer); clearInterval(pollTimer);
pollTimer = setInterval(verify, 6000); pollTimer = setInterval(verify, 6000);
startFreeAccess(); $('freeAccessMessage').textContent = 'PIX pronto. Toque em “Copiar PIX e liberar internet”; depois abra o banco e cole o código.';
$('retryFreeAccess').textContent = 'Já copiei: liberar internet';
$('retryFreeAccess').hidden = false;
} catch (e) { } catch (e) {
toast('Erro: ' + e.message); toast('Erro: ' + e.message);
} finally { } finally {
@@ -773,7 +779,16 @@
} }
$('checkBtn').addEventListener('click', verify); $('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; }
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', () => $('copyVoucher').addEventListener('click', () =>
copy('Usuário: ' + $('vUser').textContent + '\nSenha: ' + $('vPass').textContent, 'Credenciais copiadas') copy('Usuário: ' + $('vUser').textContent + '\nSenha: ' + $('vPass').textContent, 'Credenciais copiadas')
); );
@@ -916,10 +931,14 @@
} }
loadSiteConfig().then(() => { loadSiteConfig().then(() => {
if (!/^([0-9a-f]{2}:){5}[0-9a-f]{2}$/i.test(mac) || new URLSearchParams(location.search).get('free') === '1' || sessionStorage.getItem('pendingPix')) startFreeAccess(); 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 { else {
$('freeAccessMessage').textContent = 'O acesso temporário para abrir o aplicativo do banco começa após gerar o PIX. Se precisar antes, toque em liberar acesso.'; $('freeAccessMessage').textContent = pendingPix ? 'PIX pronto. Copie o código antes de liberar a internet e abrir o banco.' : 'Gere o PIX e copie o código para liberar a internet e abrir o banco. Se precisar antes, toque em liberar acesso.';
$('retryFreeAccess').textContent = 'Liberar acesso para pagamento'; $('retryFreeAccess').textContent = pendingPix ? 'Já copiei: liberar internet' : 'Liberar acesso para pagamento';
$('retryFreeAccess').hidden = false; $('retryFreeAccess').hidden = false;
} }
}); });
+44 -7
View File
@@ -5,13 +5,18 @@ import vm from 'node:vm';
const html=fs.readFileSync(new URL('../public/index.html',import.meta.url),'utf8'); const html=fs.readFileSync(new URL('../public/index.html',import.meta.url),'utf8');
const code=html.match(/<script>([\s\S]*?)<\/script>/)[1]; const code=html.match(/<script>([\s\S]*?)<\/script>/)[1];
async function portal({search,storage={},access={ok:true,authenticated:true,seconds:120},externalAvailable=true}) { async function portal({search,storage={},access={ok:true,authenticated:true,seconds:120},externalAvailable=true,clipboardAvailable=true,legacyCopy=false}) {
const ids=[...html.matchAll(/\bid="([^"]+)"/g)].map(m=>m[1]); const ids=[...html.matchAll(/\bid="([^"]+)"/g)].map(m=>m[1]);
const elements=new Map(ids.map(id=>[id,{textContent:'',hidden:false,disabled:false,value:'',innerHTML:'',classList:{toggle(){},add(){},remove(){}},addEventListener(){},appendChild(){}}])); const listeners=new Map(),clipboard=[];
const elements=new Map(ids.map(id=>[id,{textContent:'',hidden:false,disabled:false,value:'',innerHTML:'',classList:{toggle(){},add(){},remove(){}},addEventListener:(event,fn)=>listeners.set(id+':'+event,fn),appendChild(){}}]));
const requests=[],forms=[],intervals=[],navigations=[]; 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(){}}}; 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.location.href='https://hotspot.example.test/'+(search || '');
sandbox.window.location={replace:url=>navigations.push(url)}; 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)=>{ sandbox.fetch=async(path,options)=>{
requests.push({path,options}); requests.push({path,options});
if(path==='/api/config')return {ok:true,json:async()=>({hotspotIp:'10.10.10.1',ssid:'Test'})}; if(path==='/api/config')return {ok:true,json:async()=>({hotspotIp:'10.10.10.1',ssid:'Test'})};
@@ -30,7 +35,10 @@ async function portal({search,storage={},access={ok:true,authenticated:true,seco
}; };
vm.runInNewContext(code,sandbox); vm.runInNewContext(code,sandbox);
for(let i=0;i<10;i++)await new Promise(r=>setImmediate(r)); for(let i=0;i<10;i++)await new Promise(r=>setImmediate(r));
return {requests,elements,forms,intervals,navigations,checkout:async()=>{ 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]'; elements.get('payerName').value='Teste Usuario';elements.get('payerEmail').value='[email protected]';
await vm.runInNewContext('checkout("plano-1h")',sandbox); await vm.runInNewContext('checkout("plano-1h")',sandbox);
for(let i=0;i<10;i++)await new Promise(r=>setImmediate(r)); for(let i=0;i<10;i++)await new Promise(r=>setImmediate(r));
@@ -56,20 +64,25 @@ test('portal reports cooldown failures and offers retry',async()=>{
test('browsing plans does not consume the payment internet window',async()=>{ test('browsing plans does not consume the payment internet window',async()=>{
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11'}); 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.equal(p.requests.filter(r=>r.path==='/api/access/start').length,0);
assert.match(p.elements.get('freeAccessMessage').textContent,/após gerar o PIX/); assert.match(p.elements.get('freeAccessMessage').textContent,/Gere o PIX e copie/);
}); });
test('temporary internet starts after PIX is generated and QR survives a reload',async()=>{ test('generating or restoring a PIX leaves it visible without granting internet or navigating',async()=>{
const storage={}; const storage={};
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11',storage}); const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11',storage});
await p.checkout(); await p.checkout();
const paths=p.requests.map(r=>r.path); const paths=p.requests.map(r=>r.path);
assert.ok(paths.indexOf('/api/checkout')<paths.indexOf('/api/access/start')); assert.ok(paths.includes('/api/checkout'));
assert.match(p.elements.get('freeAccessMessage').textContent,/confirmada/); assert.ok(!paths.includes('/api/access/start'));
assert.equal(p.navigations.length,0);
assert.match(p.elements.get('freeAccessMessage').textContent,/Copiar PIX/);
assert.equal(JSON.parse(storage.pendingPix).paymentId,'Ptest'); assert.equal(JSON.parse(storage.pendingPix).paymentId,'Ptest');
assert.equal(p.elements.get('copiaCola').textContent,'test-pix'); assert.equal(p.elements.get('copiaCola').textContent,'test-pix');
const reloaded=await portal({search:'?mac=AA:BB:CC:DD:EE:11',storage}); const reloaded=await portal({search:'?mac=AA:BB:CC:DD:EE:11',storage});
assert.equal(reloaded.elements.get('copiaCola').textContent,'test-pix'); 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/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()=>{ test('client probes external services and reports observations without sending its token externally',async()=>{
for(const externalAvailable of [true,false]){ for(const externalAvailable of [true,false]){
@@ -99,6 +112,10 @@ test('API login navigates once to trigger captive-network revalidation and resto
const access={ok:true,authenticated:true,seconds:120,expiresAt,probeToken:'private-probe'}; 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}); const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11',storage,access});
await p.checkout(); 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); assert.equal(p.navigations.length,1);
const target=new URL(p.navigations[0]); const target=new URL(p.navigations[0]);
assert.equal(target.origin,'https://hotspot.example.test'); assert.equal(target.origin,'https://hotspot.example.test');
@@ -116,6 +133,26 @@ test('API login navigates once to trigger captive-network revalidation and resto
assert.equal(storage.freeAccessConfirmedUntil,String(expiresAt)); 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/);
// The explicit button remains available after the guest has copied manually.
await p.click('retryFreeAccess');
assert.equal(p.requests.filter(r=>r.path==='/api/access/start').length,1);
});
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()=>{ test('an expired or denied window cannot navigate, and a new window can revalidate again',async()=>{
const previous=Date.now()-1000; const previous=Date.now()-1000;
const storage={freeAccessConfirmedUntil:String(previous)}; const storage={freeAccessConfirmedUntil:String(previous)};