Activate paid Wi-Fi automatically and redesign portal with payment deadline and 45-minute wait
build-image / build-push (push) Successful in 2m59s
build-image / build-push (push) Successful in 2m59s
This commit is contained in:
1 parent
b69b3afa5d
commit
ce6e5980ec
10 files changed
+189
-37
No files matched your search
@@ -6,10 +6,10 @@ Portal de venda de acesso Wi-Fi integrado ao Mercado Pago (Orders API) e ao hots
|
|||||||
|
|
||||||
1. O MikroTik redireciona o convidado para o portal, com `?mac=...`.
|
1. O MikroTik redireciona o convidado para o portal, com `?mac=...`.
|
||||||
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.
|
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. 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.
|
3. O portal mostra o prazo configurado (padrão: 2 minutos) e exige confirmação de leitura. Ao tocar em **Copiar PIX e liberar internet**, confirma a cópia antes de autenticar pela API `/ip/hotspot/active/login`. Se a cópia falhar, mantém a tela aberta; **Já copiei: liberar internet** permite continuar após copiar manualmente ou ler o QR Code. A janela do Wi-Fi pode fechar quando o aparelho reconhece a internet: o código já estará copiado. Apenas gerar ou restaurar um PIX não consome a janela. Sem pagamento confirmado, a conexão 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 para instalações antigas com valor 300; o contador de espera é persistido no banco e não reinicia ao recarregar a página.
|
||||||
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, 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. 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. 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
|
## Instalação Docker
|
||||||
|
|
||||||
|
|||||||
+73
-13
@@ -6,9 +6,6 @@
|
|||||||
<meta name="theme-color" content="#101820">
|
<meta name="theme-color" content="#101820">
|
||||||
<title>INCTG Wi-Fi Convidados</title>
|
<title>INCTG Wi-Fi Convidados</title>
|
||||||
<link rel="icon" type="image/png" href="logo.png">
|
<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) -->
|
<!-- 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://sdk.mercadopago.com/js/v2" defer></script>
|
||||||
<script src="https://www.mercadopago.com.br/integrations/v1/security-code.js" async view="checkout"></script>
|
<script src="https://www.mercadopago.com.br/integrations/v1/security-code.js" async view="checkout"></script>
|
||||||
@@ -464,6 +461,37 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
@keyframes sk { to { background-position: -200% 0; } }
|
@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; }
|
||||||
|
#retryFreeAccess { margin-top:14px; }
|
||||||
|
.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>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
@@ -471,14 +499,19 @@
|
|||||||
<header class="brand">
|
<header class="brand">
|
||||||
<img class="brand-logo" src="logo.png" alt="INCTG — Incorpore Technology Group" width="108" height="108">
|
<img class="brand-logo" src="logo.png" alt="INCTG — Incorpore Technology Group" width="108" height="108">
|
||||||
<div>
|
<div>
|
||||||
<h1>Wi-Fi Convidados</h1>
|
<div class="eyebrow">INCTG · Wi-Fi para você</div>
|
||||||
<p class="tagline">Escolha seu plano · <strong>Pague com PIX</strong> · Conecte em segundos</p>
|
<h1>Sua conexão.<br>No seu tempo.</h1>
|
||||||
|
<p class="tagline">Escolha um plano, pague com PIX e continue conectado. Simples assim.</p>
|
||||||
|
<div class="journey" aria-label="Etapas"><span>01 · Escolha</span><span>02 · Pague com PIX</span><span>03 · Navegue</span></div>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<!-- ===== PLANOS ===== -->
|
<!-- ===== PLANOS ===== -->
|
||||||
<div class="card" style="margin-bottom:14px" role="status" aria-live="polite">
|
<div class="card access-card">
|
||||||
<p id="freeAccessMessage">Verificando acesso temporário para pagamento…</p>
|
<div class="access-heading"><strong>Internet para fazer o pagamento</strong><span id="freeCountdown" class="countdown" role="timer" aria-label="Tempo restante"></span></div>
|
||||||
|
<p id="accessRules" class="access-rules">Você tem 2 minutos de internet para pagar. Sem pagamento confirmado, o acesso termina e uma nova liberação só fica disponível 45 minutos depois.</p>
|
||||||
|
<label class="consent"><input id="accessConsent" type="checkbox"><span id="accessConsentText">Entendi o prazo para pagar e a espera de 45 minutos se o tempo acabar.</span></label>
|
||||||
|
<p id="freeAccessMessage" role="status" aria-live="polite">Preparando seu acesso…</p>
|
||||||
<p id="freeAccessProbe" hidden></p>
|
<p id="freeAccessProbe" hidden></p>
|
||||||
<button class="btn btn-ghost" id="retryFreeAccess" type="button" hidden>Tentar liberar acesso</button>
|
<button class="btn btn-ghost" id="retryFreeAccess" type="button" hidden>Tentar liberar acesso</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -570,7 +603,7 @@
|
|||||||
</svg>
|
</svg>
|
||||||
</div>
|
</div>
|
||||||
<h2 id="vTitle">Pagamento confirmado</h2>
|
<h2 id="vTitle">Pagamento confirmado</h2>
|
||||||
<p class="hint">Use os dados abaixo na tela de login do Wi-Fi.</p>
|
<p class="hint" id="paidConnectionMessage">Conectando seu aparelho ao plano comprado…</p>
|
||||||
|
|
||||||
<div class="code-box">
|
<div class="code-box">
|
||||||
<div class="lbl">Usuário</div>
|
<div class="lbl">Usuário</div>
|
||||||
@@ -582,9 +615,9 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<ol class="steps">
|
<ol class="steps">
|
||||||
<li>Toque no botão <strong>Conectar agora</strong> abaixo</li>
|
<li>Seu pagamento foi confirmado</li>
|
||||||
<li>Se pedir, conecte na rede <strong id="ssidLabel">Wi-Fi</strong></li>
|
<li>Mantenha o aparelho na rede <strong id="ssidLabel">Wi-Fi</strong></li>
|
||||||
<li>Pronto: seu acesso já estará liberado</li>
|
<li>A conexão muda automaticamente para o plano comprado</li>
|
||||||
</ol>
|
</ol>
|
||||||
|
|
||||||
<button class="btn btn-success" id="hsAutoLogin" type="button" style="margin-top:14px">Conectar agora</button>
|
<button class="btn btn-success" id="hsAutoLogin" type="button" style="margin-top:14px">Conectar agora</button>
|
||||||
@@ -608,6 +641,16 @@
|
|||||||
let selectedPlanId = null;
|
let selectedPlanId = null;
|
||||||
let mpDevice = null;
|
let mpDevice = null;
|
||||||
let checkoutBusy = false;
|
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 copiar o PIX e liberar o acesso, você terá ' + durationLabel(freeSeconds) + ' de internet para pagar. Sem pagamento confirmado, a conexão termina. Uma nova liberação só será possível ' + durationLabel(freeCooldownSeconds) + ' após o fim desse prazo. O pagamento confirmado ativa seu plano automaticamente.';
|
||||||
|
$('accessConsentText').textContent = 'Entendi: tenho ' + durationLabel(freeSeconds) + ' para pagar e, se o prazo acabar, preciso aguardar ' + durationLabel(freeCooldownSeconds) + ' para pedir mais tempo.';
|
||||||
|
}
|
||||||
|
|
||||||
const $ = (id) => document.getElementById(id);
|
const $ = (id) => document.getElementById(id);
|
||||||
|
|
||||||
@@ -756,13 +799,18 @@
|
|||||||
if (data.status === 'paid' && data.voucher) {
|
if (data.status === 'paid' && data.voucher) {
|
||||||
sessionStorage.removeItem('pendingPix');
|
sessionStorage.removeItem('pendingPix');
|
||||||
clearInterval(window.freeAccessTimer);
|
clearInterval(window.freeAccessTimer);
|
||||||
$('freeAccessMessage').textContent = 'Pagamento confirmado. Use seu voucher para conectar ao Wi-Fi.';
|
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';
|
||||||
$('retryFreeAccess').hidden = true;
|
$('retryFreeAccess').hidden = true;
|
||||||
clearInterval(pollTimer); pollTimer = null;
|
clearInterval(pollTimer); pollTimer = null;
|
||||||
$('vUser').textContent = data.voucher.user;
|
$('vUser').textContent = data.voucher.user;
|
||||||
$('vPass').textContent = data.voucher.pass;
|
$('vPass').textContent = data.voucher.pass;
|
||||||
setPill('ok', 'Pagamento aprovado');
|
setPill('ok', 'Pagamento aprovado');
|
||||||
show('voucher');
|
show('voucher');
|
||||||
|
if (!connected) pollTimer = setInterval(verify, 6000);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (['rejected', 'cancelled', 'expired'].includes(data.status)) {
|
if (['rejected', 'cancelled', 'expired'].includes(data.status)) {
|
||||||
@@ -838,6 +886,13 @@
|
|||||||
retry.hidden = false;
|
retry.hidden = false;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
const resuming = Number(sessionStorage.getItem('freeAccessConfirmedUntil') || 0) > Date.now() ||
|
||||||
|
Number(sessionStorage.getItem('freeLoginAttemptUntil') || 0) > Date.now();
|
||||||
|
if (!$('accessConsent').checked && !resuming) {
|
||||||
|
message.textContent = 'Antes de liberar a internet, confirme acima que entendeu o prazo para pagar e a espera para uma nova liberação.';
|
||||||
|
retry.hidden = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
retry.hidden = true;
|
retry.hidden = true;
|
||||||
message.textContent = 'Preparando acesso temporário para abrir o aplicativo do banco…';
|
message.textContent = 'Preparando acesso temporário para abrir o aplicativo do banco…';
|
||||||
try {
|
try {
|
||||||
@@ -848,7 +903,7 @@
|
|||||||
});
|
});
|
||||||
const d = await res.json();
|
const d = await res.json();
|
||||||
if (!res.ok) {
|
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.';
|
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.';
|
||||||
retry.hidden = false;
|
retry.hidden = false;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -873,7 +928,9 @@
|
|||||||
const deadline = Date.now() + d.seconds * 1000;
|
const deadline = Date.now() + d.seconds * 1000;
|
||||||
const update = () => {
|
const update = () => {
|
||||||
const seconds = Math.max(0, Math.ceil((deadline - Date.now()) / 1000));
|
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”.';
|
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) message.textContent += ' Para solicitar mais tempo, aguarde ' + durationLabel(freeCooldownSeconds) + '. O pagamento confirmado ativa o plano automaticamente.';
|
||||||
if (!seconds) { clearInterval(window.freeAccessTimer); retry.hidden = false; }
|
if (!seconds) { clearInterval(window.freeAccessTimer); retry.hidden = false; }
|
||||||
};
|
};
|
||||||
update(); window.freeAccessTimer = setInterval(update, 1000);
|
update(); window.freeAccessTimer = setInterval(update, 1000);
|
||||||
@@ -925,6 +982,9 @@
|
|||||||
try {
|
try {
|
||||||
const res = await fetch('/api/config');
|
const res = await fetch('/api/config');
|
||||||
const d = await res.json();
|
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 (d.ssid) $('ssidLabel').textContent = d.ssid;
|
if (d.ssid) $('ssidLabel').textContent = d.ssid;
|
||||||
if (/^(?:\d{1,3}\.){3}\d{1,3}$/.test(d.hotspotIp)) HS_LOGIN = 'http://' + d.hotspotIp + '/login';
|
if (/^(?:\d{1,3}\.){3}\d{1,3}$/.test(d.hotspotIp)) HS_LOGIN = 'http://' + d.hotspotIp + '/login';
|
||||||
} catch { /* usa padrao */ }
|
} catch { /* usa padrao */ }
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ const config = {
|
|||||||
},
|
},
|
||||||
port: parseInt(process.env.PORT || '3000', 10),
|
port: parseInt(process.env.PORT || '3000', 10),
|
||||||
freeAccessSeconds: Number(process.env.FREE_ACCESS_SECONDS || 120),
|
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',
|
ssidName: process.env.SSID_NAME || 'Internet Gratis',
|
||||||
hotspotIp: process.env.HOTSPOT_IP || '10.10.10.1',
|
hotspotIp: process.env.HOTSPOT_IP || '10.10.10.1',
|
||||||
baseUrl: process.env.BASE_URL || 'http://192.168.3.100:3000',
|
baseUrl: process.env.BASE_URL || 'http://192.168.3.100:3000',
|
||||||
|
|||||||
+10
-7
@@ -10,7 +10,7 @@ import { fileURLToPath } from 'node:url';
|
|||||||
import config from './config.js';
|
import config from './config.js';
|
||||||
import { initDb, getDb, saveDb, genCode } from './db.js';
|
import { initDb, getDb, saveDb, genCode } from './db.js';
|
||||||
import { initMp, createPixPayment, getPaymentStatus, cancelOrder, validCpf } from './mp.js';
|
import { initMp, createPixPayment, getPaymentStatus, cancelOrder, validCpf } from './mp.js';
|
||||||
import { 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));
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||||
export const app = express();
|
export const app = express();
|
||||||
@@ -36,12 +36,13 @@ initDb();
|
|||||||
saveDb();
|
saveDb();
|
||||||
initMp();
|
initMp();
|
||||||
|
|
||||||
const { checkPayment, checks } = paymentService({ getDb, saveDb, getPaymentStatus, rosCommand, createHotspotUser });
|
const { checkPayment, checks } = paymentService({ getDb, saveDb, getPaymentStatus, rosCommand, createHotspotUser, activatePaidAccess });
|
||||||
|
|
||||||
// ===== Rotas =====
|
// ===== Rotas =====
|
||||||
|
|
||||||
// ===== Internet temporaria para pagar (bypass do hotspot) =====
|
// ===== Internet temporaria para pagar (bypass do hotspot) =====
|
||||||
const accessLocks = new Set();
|
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) => {
|
app.post('/api/access/start', async (req, res) => {
|
||||||
const mac = typeof req.body?.mac === 'string' ? req.body.mac.toUpperCase() : '';
|
const mac = typeof req.body?.mac === 'string' ? req.body.mac.toUpperCase() : '';
|
||||||
if (!validMac(mac)) return res.status(400).json({ error: 'mac obrigatorio' });
|
if (!validMac(mac)) return res.status(400).json({ error: 'mac obrigatorio' });
|
||||||
@@ -53,8 +54,8 @@ app.post('/api/access/start', async (req, res) => {
|
|||||||
const prev = (db.tempAccess || []).find((t) => t.mac === mac);
|
const prev = (db.tempAccess || []).find((t) => t.mac === mac);
|
||||||
|
|
||||||
// reusa a janela criada ha menos de X minutos (evita abuso de janelas ilimitadas)
|
// reusa a janela criada ha menos de X minutos (evita abuso de janelas ilimitadas)
|
||||||
if (prev && now - Date.parse(prev.createdAt) < config.freeAccessCooldownSeconds * 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((Date.parse(prev.createdAt) + config.freeAccessCooldownSeconds * 1000 - now) / 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((accessRetryAt(prev) - now) / 1000) });
|
||||||
const previousUrl = new URL(prev.loginUrl);
|
const previousUrl = new URL(prev.loginUrl);
|
||||||
if (!prev.probeToken) { prev.probeToken = crypto.randomBytes(24).toString('hex'); saveDb(); }
|
if (!prev.probeToken) { prev.probeToken = crypto.randomBytes(24).toString('hex'); saveDb(); }
|
||||||
let authenticated = false;
|
let authenticated = false;
|
||||||
@@ -80,6 +81,7 @@ app.post('/api/access/start', async (req, res) => {
|
|||||||
loginUrl,
|
loginUrl,
|
||||||
createdAt: new Date(startedAt).toISOString(),
|
createdAt: new Date(startedAt).toISOString(),
|
||||||
expiresAt: startedAt + config.freeAccessSeconds * 1000,
|
expiresAt: startedAt + config.freeAccessSeconds * 1000,
|
||||||
|
cooldownUntil: startedAt + (config.freeAccessSeconds + config.freeAccessCooldownSeconds) * 1000,
|
||||||
probeToken: crypto.randomBytes(24).toString('hex'),
|
probeToken: crypto.randomBytes(24).toString('hex'),
|
||||||
});
|
});
|
||||||
saveDb();
|
saveDb();
|
||||||
@@ -133,7 +135,7 @@ app.post('/api/reconcile', adminAuth, async (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
app.get('/api/config', (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 });
|
||||||
});
|
});
|
||||||
|
|
||||||
app.get('/api/plans', (req, res) => {
|
app.get('/api/plans', (req, res) => {
|
||||||
@@ -224,6 +226,7 @@ app.get('/api/status/:id', async (req, res) => {
|
|||||||
status: payment.status,
|
status: payment.status,
|
||||||
orderId: payment.mpId,
|
orderId: payment.mpId,
|
||||||
voucher: payment.voucher,
|
voucher: payment.voucher,
|
||||||
|
connection: payment.connection,
|
||||||
planName: getDb().plans.find((p) => p.id === payment.planId)?.name,
|
planName: getDb().plans.find((p) => p.id === payment.planId)?.name,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -273,7 +276,7 @@ let polling = false;
|
|||||||
setInterval(async () => {
|
setInterval(async () => {
|
||||||
if (polling) return;
|
if (polling) return;
|
||||||
polling = true;
|
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; }
|
finally { polling = false; }
|
||||||
}, 15000).unref();
|
}, 15000).unref();
|
||||||
let cleaning = false;
|
let cleaning = false;
|
||||||
@@ -288,7 +291,7 @@ setInterval(async () => {
|
|||||||
catch (e) { console.error('[ACESSO]', e.message); }
|
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();
|
saveDb();
|
||||||
} catch (e) { console.error('[LIMPEZA]', e.message); } finally { cleaning = false; }
|
} catch (e) { console.error('[LIMPEZA]', e.message); } finally { cleaning = false; }
|
||||||
}, 15000).unref();
|
}, 15000).unref();
|
||||||
|
|||||||
+18
-7
@@ -1,8 +1,22 @@
|
|||||||
import { genCode } from './db.js';
|
import { genCode } from './db.js';
|
||||||
|
|
||||||
// One application process owns the JSON database and these per-payment locks.
|
// 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();
|
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) {
|
async function fulfill(payment) {
|
||||||
if (payment.voucher) return payment;
|
if (payment.voucher) return payment;
|
||||||
if (!payment.uptime) throw new Error('Pagamento sem limite de uso');
|
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.status = 'paid';
|
||||||
payment.paidAt = new Date().toISOString();
|
payment.paidAt = new Date().toISOString();
|
||||||
delete payment.provisioning;
|
delete payment.provisioning;
|
||||||
if (payment.mac) {
|
|
||||||
const temp = (getDb().tempAccess || []).find(t => t.mac === payment.mac);
|
|
||||||
if (temp) temp.expiresAt = Date.now();
|
|
||||||
}
|
|
||||||
saveDb();
|
saveDb();
|
||||||
return payment;
|
return connect(payment);
|
||||||
}
|
}
|
||||||
async function checkPayment(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);
|
if (checks.has(payment.id)) return checks.get(payment.id);
|
||||||
const task = (async () => {
|
const task = (async () => {
|
||||||
try {
|
try {
|
||||||
|
if (payment.status === 'paid') return await connect(payment);
|
||||||
const st = await getPaymentStatus(payment.mpId, payment);
|
const st = await getPaymentStatus(payment.mpId, payment);
|
||||||
if (st === 'approved') return await fulfill(payment);
|
if (st === 'approved') return await fulfill(payment);
|
||||||
if (['rejected', 'cancelled', 'expired', 'refunded'].includes(st)) { payment.status = st; saveDb(); }
|
if (['rejected', 'cancelled', 'expired', 'refunded'].includes(st)) { payment.status = st; saveDb(); }
|
||||||
|
|||||||
@@ -236,6 +236,26 @@ export async function loginPaymentAccess({ mac, user, pass }) {
|
|||||||
return temporaryAccessActive(mac);
|
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) {
|
function pickField(row, key) {
|
||||||
const v = (row || []).find((w) => w.startsWith(key));
|
const v = (row || []).find((w) => w.startsWith(key));
|
||||||
return v ? v.slice(key.length) : null;
|
return v ? v.slice(key.length) : null;
|
||||||
|
|||||||
@@ -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)));
|
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.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;
|
const dataDir=fs.mkdtempSync(path.join(os.tmpdir(),'hotspot-test-'));process.env.DATA_DIR=dataDir;
|
||||||
t.after(()=>fs.rmSync(dataDir,{recursive:true,force:true}));
|
t.after(()=>fs.rmSync(dataDir,{recursive:true,force:true}));
|
||||||
const { app }=await import('../src/index.js');
|
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)});
|
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);
|
assert.equal((await fetch(base+'/api/admin/users')).status,401);
|
||||||
const { default: config } = await import('../src/config.js');
|
const { default: config } = await import('../src/config.js');
|
||||||
|
assert.equal(config.freeAccessCooldownSeconds,2700);
|
||||||
const originalToken = config.adminToken;
|
const originalToken = config.adminToken;
|
||||||
config.adminToken = 'replace-with-at-least-32-random-characters';
|
config.adminToken = 'replace-with-at-least-32-random-characters';
|
||||||
assert.equal((await request('/api/admin/users')).status,503);
|
assert.equal((await request('/api/admin/users')).status,503);
|
||||||
@@ -89,9 +91,21 @@ test('admin API authenticates, creates, lists, blocks, disconnects and exports w
|
|||||||
assert.equal(commands.filter(c=>c[0]==='/ip/hotspot/active/login').length,loginCount);
|
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;
|
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/report','POST',{mac:'AA:BB:CC:DD:EE:11',token:temporary.probeToken,results:probeResults})).status,410);
|
assert.equal((await request('/api/access/report','POST',{mac:'AA:BB:CC:DD:EE:11',token:temporary.probeToken,results:probeResults})).status,410);
|
||||||
assert.equal((await request('/api/access/start','POST',{mac:'AA:BB:CC:DD:EE:11'})).status,429);
|
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=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;
|
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'});
|
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'));
|
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'));
|
trap=true;res=await request('/api/admin/users');assert.equal(res.status,500);assert.ok(!(await res.text()).includes('simulated failure'));
|
||||||
|
|||||||
@@ -5,13 +5,14 @@ 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,clipboardAvailable=true,legacyCopy=false}) {
|
async function portal({search,storage={},access={ok:true,authenticated:true,seconds:120},externalAvailable=true,clipboardAvailable=true,legacyCopy=false,consent=true,siteConfig={},paymentStatus={status:'pending'}}) {
|
||||||
const ids=[...html.matchAll(/\bid="([^"]+)"/g)].map(m=>m[1]);
|
const ids=[...html.matchAll(/\bid="([^"]+)"/g)].map(m=>m[1]);
|
||||||
const listeners=new Map(),clipboard=[];
|
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 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 || '');
|
||||||
|
elements.get('accessConsent').checked=consent;
|
||||||
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.navigator.clipboard={writeText:async text=>{if(!clipboardAvailable)throw new Error('Clipboard denied');clipboard.push(text);}};
|
||||||
sandbox.document.body.appendChild=()=>{};
|
sandbox.document.body.appendChild=()=>{};
|
||||||
@@ -19,11 +20,11 @@ async function portal({search,storage={},access={ok:true,authenticated:true,seco
|
|||||||
sandbox.document.execCommand=()=>legacyCopy;
|
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',...siteConfig})};
|
||||||
if(path==='/api/plans')return {ok:true,json:async()=>[]};
|
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/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/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()=>({status:'pending'})};
|
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==='/api/access/report')return {ok:true,json:async()=>({ok:true})};
|
||||||
if(path.startsWith('https://www.gstatic.com/') || path.startsWith('https://www.apple.com/')) {
|
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.
|
// Fetch rejects no-cors requests unless redirect mode is follow, before any network traffic.
|
||||||
@@ -58,7 +59,7 @@ test('direct portal URL without MAC cannot silently claim temporary access',asyn
|
|||||||
});
|
});
|
||||||
test('portal reports cooldown failures and offers retry',async()=>{
|
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}});
|
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,/180 segundos/);
|
assert.match(p.elements.get('freeAccessMessage').textContent,/3 minutos/);
|
||||||
assert.equal(p.elements.get('retryFreeAccess').hidden,false);
|
assert.equal(p.elements.get('retryFreeAccess').hidden,false);
|
||||||
});
|
});
|
||||||
test('browsing plans does not consume the payment internet window',async()=>{
|
test('browsing plans does not consume the payment internet window',async()=>{
|
||||||
@@ -164,3 +165,25 @@ test('an expired or denied window cannot navigate, and a new window can revalida
|
|||||||
const next=await portal({search,storage,access:{ok:true,authenticated:true,seconds:120,expiresAt:Date.now()+120000}});
|
const next=await portal({search,storage,access:{ok:true,authenticated:true,seconds:120,expiresAt:Date.now()+120000}});
|
||||||
assert.equal(next.navigations.length,1);
|
assert.equal(next.navigations.length,1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('rules use the configured payment duration and require acknowledgement before access',async()=>{
|
||||||
|
const p=await portal({search:'?mac=AA:BB:CC:DD:EE:11',consent:false,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/);
|
||||||
|
await p.checkout();await p.click('copyBtn');
|
||||||
|
assert.equal(p.requests.filter(r=>r.path==='/api/access/start').length,0);
|
||||||
|
assert.match(p.elements.get('freeAccessMessage').textContent,/confirme acima/);
|
||||||
|
p.elements.get('accessConsent').checked=true;
|
||||||
|
await p.click('retryFreeAccess');
|
||||||
|
assert.equal(p.requests.filter(r=>r.path==='/api/access/start').length,1);
|
||||||
|
});
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -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 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');
|
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);
|
||||||
|
});
|
||||||
+1
-1
@@ -36,4 +36,4 @@ services:
|
|||||||
TRUST_PROXY: "${TRUST_PROXY:-}"
|
TRUST_PROXY: "${TRUST_PROXY:-}"
|
||||||
HOTSPOT_IP: "10.10.10.1"
|
HOTSPOT_IP: "10.10.10.1"
|
||||||
FREE_ACCESS_SECONDS: "120"
|
FREE_ACCESS_SECONDS: "120"
|
||||||
FREE_ACCESS_COOLDOWN_SECONDS: "300"
|
FREE_ACCESS_COOLDOWN_SECONDS: "2700"
|
||||||
Reference in new issue
Block a user