78 lines
5.5 KiB
JavaScript
78 lines
5.5 KiB
JavaScript
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import crypto from 'node:crypto';
|
|
import { validMac, validatePlans, csvCell } from '../src/security.js';
|
|
import { verifyWebhook } from '../src/webhook.js';
|
|
import { verifyPaidOrder, orderStatus } from '../src/mp.js';
|
|
import { paymentService } from '../src/payments.js';
|
|
|
|
test('webhook accepts signed notifications and rejects forged, expired and modified IDs', () => {
|
|
const ts = String(Date.now()), secret = 'secret', id = 'ORD123';
|
|
const v1 = crypto.createHmac('sha256', secret).update(`id:${id.toLowerCase()};request-id:req1;ts:${ts};`).digest('hex');
|
|
const req = { query: { 'data.id': id }, headers: { 'x-request-id': 'req1', 'x-signature': `ts=${ts},v1=${v1}` } };
|
|
assert.equal(verifyWebhook(req, secret), true);
|
|
assert.equal(verifyWebhook(req, 'wrong'), false);
|
|
req.query['data.id'] = 'ORD456'; assert.equal(verifyWebhook(req, secret), false);
|
|
req.query['data.id'] = id; req.headers['x-signature'] = `ts=1,v1=${v1}`;
|
|
assert.equal(verifyWebhook(req, secret), false);
|
|
});
|
|
test('only the expected reference and fully paid amount are accepted', () => {
|
|
const payment = { id: 'P1', price: 3 };
|
|
const data = { external_reference: 'P1', total_amount: '3.00', total_paid_amount: '3.00' };
|
|
assert.doesNotThrow(() => verifyPaidOrder(data, payment));
|
|
for (const patch of [{ external_reference: 'P2' }, { total_amount: '0.01' }, { total_paid_amount: '0.01' }, { total_paid_amount: undefined }, { total_paid_amount: 'NaN' }]) assert.throws(() => verifyPaidOrder({ ...data, ...patch }, payment));
|
|
});
|
|
test('validates plan changes and neutralizes CSV formulas', () => {
|
|
const p = { id:'p1',name:'Hora',price:3,profile:'pix-1h',uptime:'1h',speed:'5M/1M',active:true };
|
|
assert.equal(validatePlans([p]),true);
|
|
for (const patch of [{price:-1},{price:'3'},{price:NaN},{price:3.001},{uptime:'0h'},{profile:'bad\nvalue'}]) assert.equal(validatePlans([{...p,...patch}]),false);
|
|
assert.equal(validatePlans([p,p]),false);
|
|
assert.equal(validMac('AA:BB:CC:DD:EE:FF'),true); assert.equal(validMac('anything'),false);
|
|
assert.equal(csvCell('=HYPERLINK("bad")'),'"\'=HYPERLINK(""bad"")"');
|
|
});
|
|
test('normalizes Orders API cancellations, failures, expirations and refunds', () => {
|
|
for (const [status, expected] of [['canceled','cancelled'],['failed','rejected'],['refunded','refunded'],['processed','approved'],['action_required','pending']]) assert.equal(orderStatus({status}),expected);
|
|
assert.equal(orderStatus({status:'canceled',status_detail:'expired'}),'expired');
|
|
assert.equal(orderStatus({status:'processed',transactions:{payments:[{status:'refunded'}]}}),'refunded');
|
|
});
|
|
test('simultaneous confirmations issue only one voucher', async () => {
|
|
let creates=0, queries=0;
|
|
const payment={id:'P1',mpId:'ORD1',status:'pending',profile:'pix-1h',uptime:'1h'};
|
|
const svc=paymentService({getDb:()=>({}),saveDb:()=>{},getPaymentStatus:async()=>{queries++;await new Promise(r=>setTimeout(r,10));return 'approved';},rosCommand:async()=>[],createHotspotUser:async()=>{creates++;}});
|
|
await Promise.all(Array.from({length:10},()=>svc.checkPayment(payment)));
|
|
assert.equal(queries,1);assert.equal(creates,1);assert.equal(payment.status,'paid');
|
|
});
|
|
test('RouterOS timeout retries reuse the persisted username without duplicating the voucher', async () => {
|
|
let created=null, calls=0;
|
|
const payment={id:'P2',mpId:'ORD2',status:'pending',profile:'pix-1h',uptime:'1h'};
|
|
const svc=paymentService({getDb:()=>({}),saveDb:()=>{},getPaymentStatus:async()=> 'approved',rosCommand:async()=>created ? [['=comment=pix:P2']] : [],createHotspotUser:async name=>{created=name;calls++;throw new Error('timeout after create');}});
|
|
await svc.checkPayment(payment);assert.equal(payment.status,'pending');assert.ok(payment.provisioning);
|
|
await svc.checkPayment(payment);assert.equal(payment.status,'paid');assert.equal(payment.voucher.user,created);assert.equal(calls,1);
|
|
});
|
|
test('unconfirmed payments never provision users', async () => {
|
|
let creates=0;
|
|
const svc=paymentService({getDb:()=>({}),saveDb:()=>{},getPaymentStatus:async()=>{throw new Error('MP unavailable');},rosCommand:async()=>[],createHotspotUser:async()=>{creates++;}});
|
|
const p={id:'P3',mpId:'ORD3',status:'pending'};await svc.checkPayment(p);assert.equal(creates,0);assert.equal(p.status,'pending');
|
|
});
|
|
|
|
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);
|
|
});
|