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

+30 -11
View File
@@ -533,7 +533,7 @@
<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>
<p>Copie o PIX antes de abrir o banco. Ao liberar a internet, esta janela pode fechar automaticamente.</p>
</div>
<div class="qr-panel">
@@ -543,7 +543,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 PIX e liberar internet</button>
<button class="btn btn-primary" id="checkBtn" type="button">Já paguei</button>
</div>
@@ -641,16 +641,20 @@
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) {
@@ -724,7 +728,9 @@
clearInterval(pollTimer);
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) {
toast('Erro: ' + e.message);
} finally {
@@ -773,7 +779,16 @@
}
$('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', () =>
copy('Usuário: ' + $('vUser').textContent + '\nSenha: ' + $('vPass').textContent, 'Credenciais copiadas')
);
@@ -916,10 +931,14 @@
}
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 {
$('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.';
$('retryFreeAccess').textContent = 'Liberar acesso para pagamento';
$('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 = pendingPix ? 'Já copiei: liberar internet' : 'Liberar acesso para pagamento';
$('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 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 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 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'})};
@@ -30,7 +35,10 @@ async function portal({search,storage={},access={ok:true,authenticated:true,seco
};
vm.runInNewContext(code,sandbox);
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]';
await vm.runInNewContext('checkout("plano-1h")',sandbox);
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()=>{
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,/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 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.indexOf('/api/checkout')<paths.indexOf('/api/access/start'));
assert.match(p.elements.get('freeAccessMessage').textContent,/confirmada/);
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 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]){
@@ -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 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');
@@ -116,6 +133,26 @@ test('API login navigates once to trigger captive-network revalidation and resto
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()=>{
const previous=Date.now()-1000;
const storage={freeAccessConfirmedUntil:String(previous)};