chore: super deep scanning cleanup - remove obsolete debug scripts, redundant components, and temporary files
This commit is contained in:
1 parent
97d2c89c15
commit
a577f2d672
189 files changed
-11112
No files matched your search
@@ -1,175 +0,0 @@
|
||||
// test/agent_geolocation_test.js
|
||||
const mongoose = require('../backend/node_modules/mongoose');
|
||||
const path = require('path');
|
||||
|
||||
// Load environment variables
|
||||
require('dotenv').config({ path: path.join(__dirname, '../.env.local') });
|
||||
|
||||
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/backone_dpi';
|
||||
|
||||
const { CustomAgentLocation, DeviceStat, Flow } = require('../backend/models/Schemas');
|
||||
|
||||
let testCount = 0;
|
||||
let passedCount = 0;
|
||||
|
||||
function assert(label, condition) {
|
||||
testCount++;
|
||||
if (condition) {
|
||||
console.log(` ✓ PASSED: ${label}`);
|
||||
passedCount++;
|
||||
} else {
|
||||
console.error(` ✗ FAILED: ${label}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function runTests() {
|
||||
console.log('\n=========================================');
|
||||
console.log(' RUNNING TDD TESTS FOR GEOLOCATION & FLOWS');
|
||||
console.log('=========================================\n');
|
||||
|
||||
try {
|
||||
// 1. Connect to DB
|
||||
await mongoose.connect(MONGODB_URI);
|
||||
console.log('✓ Connected to MongoDB');
|
||||
|
||||
// 2. Validate Geolocation Seeding
|
||||
const count = await CustomAgentLocation.countDocuments();
|
||||
assert('CustomAgentLocation collection should have seeded documents', count >= 3);
|
||||
|
||||
const balarajaLoc = await CustomAgentLocation.findOne({ agent_uuid: 'F6-2V-DT-8A' });
|
||||
assert('CPI Balaraja Agent location should exist', !!balarajaLoc);
|
||||
if (balarajaLoc) {
|
||||
assert('CPI Balaraja latitude matches', balarajaLoc.latitude === -6.2263304);
|
||||
assert('CPI Balaraja longitude matches', balarajaLoc.longitude === 106.4247322);
|
||||
assert('CPI Balaraja belongs to SIAB site', balarajaLoc.site_uuid === '6681452d_9cae_4ff4_8ae8_0d504774265e');
|
||||
}
|
||||
|
||||
const cibuburLoc = await CustomAgentLocation.findOne({ agent_uuid: '2F-TF-1D-GK' });
|
||||
assert('JRP Cibubur Agent location should exist', !!cibuburLoc);
|
||||
if (cibuburLoc) {
|
||||
assert('JRP Cibubur latitude matches', cibuburLoc.latitude === -6.3763318);
|
||||
assert('JRP Cibubur longitude matches', cibuburLoc.longitude === 106.8983017);
|
||||
}
|
||||
|
||||
const ifgLoc = await CustomAgentLocation.findOne({ agent_uuid: '8A-V3-PB-85' });
|
||||
assert('IFG LT.18 Agent location should exist', !!ifgLoc);
|
||||
if (ifgLoc) {
|
||||
assert('IFG LT.18 latitude matches', ifgLoc.latitude === -6.2253265);
|
||||
assert('IFG LT.18 longitude matches', ifgLoc.longitude === 106.8061484);
|
||||
}
|
||||
|
||||
// 3. Test Location Updates (Simulation of POST API)
|
||||
const testUuid = 'TEST-AGENT-UUID';
|
||||
const testSite = 'test-site-uuid';
|
||||
|
||||
// Remove if exists
|
||||
await CustomAgentLocation.deleteOne({ agent_uuid: testUuid });
|
||||
|
||||
const updated = await CustomAgentLocation.findOneAndUpdate(
|
||||
{ agent_uuid: testUuid },
|
||||
{
|
||||
agent_uuid: testUuid,
|
||||
site_uuid: testSite,
|
||||
latitude: -6.1234,
|
||||
longitude: 106.1234,
|
||||
label: 'Test Location Label'
|
||||
},
|
||||
{ new: true, upsert: true }
|
||||
);
|
||||
assert('Location upsert should return the saved document', !!updated);
|
||||
assert('Upserted latitude matches', updated.latitude === -6.1234);
|
||||
assert('Upserted longitude matches', updated.longitude === 106.1234);
|
||||
assert('Upserted label matches', updated.label === 'Test Location Label');
|
||||
|
||||
// 4. Test Location Reset (Simulation of DELETE API)
|
||||
const delRes = await CustomAgentLocation.deleteOne({ agent_uuid: testUuid });
|
||||
assert('Location delete should succeed', delRes.deletedCount > 0);
|
||||
|
||||
const checkedDel = await CustomAgentLocation.findOne({ agent_uuid: testUuid });
|
||||
assert('Location should no longer exist after delete', !checkedDel);
|
||||
|
||||
// 5. Test Inter-Agent Flow Aggregation Logic
|
||||
// Let's seed a mock device belonging to Cibubur agent and a flow from Balaraja to Cibubur's device IP.
|
||||
const mockDestIp = '192.168.99.123';
|
||||
|
||||
// Cleanup if existing
|
||||
await DeviceStat.deleteOne({ ip_address: mockDestIp });
|
||||
await Flow.deleteMany({ dst_ip: mockDestIp });
|
||||
|
||||
// Seed mock device monitored by Cibubur agent (2F-TF-1D-GK)
|
||||
await DeviceStat.create({
|
||||
timestamp: new Date(),
|
||||
ip_address: mockDestIp,
|
||||
agent_uuid: '2F-TF-1D-GK',
|
||||
site_uuid: '6681452d_9cae_4ff4_8ae8_0d504774265e',
|
||||
mac_address: '00:11:22:33:44:55',
|
||||
});
|
||||
|
||||
// Seed mock flow from Balaraja agent (F6-2V-DT-8A) to mockDestIp
|
||||
await Flow.create({
|
||||
timestamp: new Date(),
|
||||
agent_uuid: 'F6-2V-DT-8A',
|
||||
site_uuid: '6681452d_9cae_4ff4_8ae8_0d504774265e',
|
||||
src_ip: '192.168.10.50',
|
||||
dst_ip: mockDestIp,
|
||||
download: 15000000,
|
||||
upload: 5000000,
|
||||
});
|
||||
|
||||
// Run the aggregation logic
|
||||
const devices = await DeviceStat.find({ site_uuid: '6681452d_9cae_4ff4_8ae8_0d504774265e' }).select('ip_address agent_uuid').lean();
|
||||
const deviceIpToAgent = {};
|
||||
for (const dev of devices) {
|
||||
if (dev.ip_address && dev.agent_uuid) {
|
||||
deviceIpToAgent[dev.ip_address] = dev.agent_uuid;
|
||||
}
|
||||
}
|
||||
|
||||
const flows = await Flow.find({ site_uuid: '6681452d_9cae_4ff4_8ae8_0d504774265e' }).select('agent_uuid src_ip dst_ip download upload').lean();
|
||||
|
||||
const flowMap = {};
|
||||
for (const flow of flows) {
|
||||
const srcAgent = flow.agent_uuid;
|
||||
const dstAgent = deviceIpToAgent[flow.dst_ip];
|
||||
|
||||
if (srcAgent && dstAgent && srcAgent !== dstAgent) {
|
||||
const key = `${srcAgent}->${dstAgent}`;
|
||||
if (!flowMap[key]) {
|
||||
flowMap[key] = {
|
||||
source: srcAgent,
|
||||
target: dstAgent,
|
||||
bytes: 0,
|
||||
flowsCount: 0
|
||||
};
|
||||
}
|
||||
flowMap[key].bytes += ((flow.download || 0) + (flow.upload || 0));
|
||||
flowMap[key].flowsCount += 1;
|
||||
}
|
||||
}
|
||||
|
||||
const result = Object.values(flowMap);
|
||||
assert('Inter-agent flows aggregation should detect flows', result.length > 0);
|
||||
|
||||
const detectedFlow = result.find(f => f.source === 'F6-2V-DT-8A' && f.target === '2F-TF-1D-GK');
|
||||
assert('Mock flow from Balaraja to Cibubur should be detected', !!detectedFlow);
|
||||
if (detectedFlow) {
|
||||
assert('Mock flow bytes matches (15MB down + 5MB up = 20MB)', detectedFlow.bytes >= 20000000);
|
||||
assert('Mock flow connection count is correct', detectedFlow.flowsCount >= 1);
|
||||
}
|
||||
|
||||
// Cleanup mock telemetry
|
||||
await DeviceStat.deleteOne({ ip_address: mockDestIp });
|
||||
await Flow.deleteMany({ dst_ip: mockDestIp });
|
||||
|
||||
console.log('\n=========================================');
|
||||
console.log(` RESULT: ${passedCount} / ${testCount} tests passed.`);
|
||||
console.log('=========================================\n');
|
||||
|
||||
await mongoose.disconnect();
|
||||
} catch (err) {
|
||||
console.error('TDD Test run error:', err);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
runTests();
|
||||
@@ -1,101 +0,0 @@
|
||||
// test/analyze_inter_agent_flows.js — diagnostic script
|
||||
// Checks if there are real inter-agent flows in MongoDB
|
||||
|
||||
const mongoose = require('../backend/node_modules/mongoose');
|
||||
const path = require('path');
|
||||
require('dotenv').config({ path: path.join(__dirname, '../.env.local') });
|
||||
|
||||
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/backone_dpi';
|
||||
const { DeviceStat, Flow } = require('../backend/models/Schemas');
|
||||
const { CustomAgentLocation } = require('../backend/models/SchemasAux');
|
||||
|
||||
async function run() {
|
||||
await mongoose.connect(MONGODB_URI);
|
||||
console.log('\n✓ Connected to MongoDB\n');
|
||||
|
||||
const SIAB_SITE = '6681452d_9cae_4ff4_8ae8_0d504774265e';
|
||||
|
||||
// 1. List registered agent coordinates
|
||||
const locations = await CustomAgentLocation.find({ site_uuid: SIAB_SITE }).lean();
|
||||
const agentUuids = locations.map(l => l.agent_uuid);
|
||||
console.log(`=== Agent Locations Registered (${locations.length}) ===`);
|
||||
for (const loc of locations) {
|
||||
console.log(` • ${loc.agent_uuid} → ${loc.label || '(no label)'} [${loc.latitude}, ${loc.longitude}]`);
|
||||
}
|
||||
|
||||
// 2. Build IP → agent_uuid map from DeviceStat
|
||||
const devices = await DeviceStat.find({ site_uuid: SIAB_SITE }).select('ip_address agent_uuid').lean();
|
||||
const ipToAgent = {};
|
||||
for (const d of devices) {
|
||||
if (d.ip_address && d.agent_uuid) ipToAgent[d.ip_address] = d.agent_uuid;
|
||||
}
|
||||
console.log(`\n=== DeviceStat Records (total ${devices.length}) ===`);
|
||||
const agentDeviceCount = {};
|
||||
for (const [ip, agent] of Object.entries(ipToAgent)) {
|
||||
agentDeviceCount[agent] = (agentDeviceCount[agent] || 0) + 1;
|
||||
}
|
||||
for (const [agent, count] of Object.entries(agentDeviceCount)) {
|
||||
console.log(` • Agent ${agent}: ${count} unique IP(s) tracked`);
|
||||
}
|
||||
|
||||
// 3. Sample flows to see dst_ip patterns
|
||||
const since24h = new Date(Date.now() - 24 * 60 * 60 * 1000);
|
||||
const flowCount = await Flow.countDocuments({ site_uuid: SIAB_SITE, timestamp: { $gte: since24h } });
|
||||
const flows = await Flow.find({ site_uuid: SIAB_SITE, timestamp: { $gte: since24h } })
|
||||
.select('agent_uuid src_ip dst_ip download upload app_label')
|
||||
.limit(200)
|
||||
.lean();
|
||||
|
||||
console.log(`\n=== Flows in Last 24h: ${flowCount} total (inspecting up to 200) ===`);
|
||||
|
||||
const interAgentFlowMap = {};
|
||||
let matchCount = 0;
|
||||
|
||||
for (const flow of flows) {
|
||||
const srcAgent = flow.agent_uuid;
|
||||
const dstAgent = ipToAgent[flow.dst_ip];
|
||||
if (srcAgent && dstAgent && srcAgent !== dstAgent) {
|
||||
matchCount++;
|
||||
const key = `${srcAgent} → ${dstAgent}`;
|
||||
if (!interAgentFlowMap[key]) {
|
||||
interAgentFlowMap[key] = { bytes: 0, count: 0, examples: [] };
|
||||
}
|
||||
interAgentFlowMap[key].bytes += (flow.download || 0) + (flow.upload || 0);
|
||||
interAgentFlowMap[key].count++;
|
||||
if (interAgentFlowMap[key].examples.length < 2) {
|
||||
interAgentFlowMap[key].examples.push({ src: flow.src_ip, dst: flow.dst_ip, app: flow.app_label });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`\n=== Inter-Agent Flows Detected: ${matchCount} (from ${flows.length} sampled) ===`);
|
||||
if (Object.keys(interAgentFlowMap).length > 0) {
|
||||
for (const [pair, data] of Object.entries(interAgentFlowMap)) {
|
||||
const mb = (data.bytes / 1024 / 1024).toFixed(2);
|
||||
console.log(` ✓ ${pair} — ${data.count} flows, ${mb} MB`);
|
||||
for (const ex of data.examples) {
|
||||
console.log(` Example: ${ex.src} → ${ex.dst} (${ex.app || 'Unclassified'})`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.log(' ✗ No inter-agent flows detected in sampled data.');
|
||||
console.log('\n — Checking sample of dst_ip values that appear in flows...');
|
||||
const dstIps = [...new Set(flows.map(f => f.dst_ip).filter(Boolean))].slice(0, 10);
|
||||
console.log(' dst_ip samples:', dstIps);
|
||||
const matched = dstIps.filter(ip => ipToAgent[ip]);
|
||||
console.log(' dst_ip matched to agents:', matched.map(ip => `${ip} → ${ipToAgent[ip]}`));
|
||||
}
|
||||
|
||||
// 4. Check if any flows have dst_ip in the devicestats table at all
|
||||
const allDstIps = [...new Set(flows.map(f => f.dst_ip).filter(Boolean))];
|
||||
let trackedCount = 0;
|
||||
for (const ip of allDstIps) {
|
||||
if (ipToAgent[ip]) trackedCount++;
|
||||
}
|
||||
console.log(`\n=== dst_ip Resolution: ${trackedCount} / ${allDstIps.length} unique dst IPs found in DeviceStat ===`);
|
||||
|
||||
await mongoose.disconnect();
|
||||
console.log('\n✓ Done.\n');
|
||||
}
|
||||
|
||||
run().catch(err => { console.error(err); process.exit(1); });
|
||||
@@ -1,15 +0,0 @@
|
||||
const mongoose = require('mongoose');
|
||||
const { LookupApp } = require('../backend/models/Schemas');
|
||||
|
||||
async function main() {
|
||||
const uri = 'mongodb://127.0.0.1:27017/backone_dpi';
|
||||
await mongoose.connect(uri);
|
||||
console.log('Connected to:', mongoose.connection.name);
|
||||
|
||||
const count = await LookupApp.countDocuments({});
|
||||
console.log('LookupApp model count in backend schema:', count);
|
||||
|
||||
await mongoose.disconnect();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,19 +0,0 @@
|
||||
const proxyMongoose = require('../proxy/node_modules/mongoose');
|
||||
require('dotenv').config({ path: './.env.local' });
|
||||
|
||||
async function main() {
|
||||
const uri = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/backone_dpi';
|
||||
await proxyMongoose.connect(uri);
|
||||
console.log('--- CONNECTION DETAILS ---');
|
||||
console.log('Host:', proxyMongoose.connection.host);
|
||||
console.log('Port:', proxyMongoose.connection.port);
|
||||
console.log('DB Name:', proxyMongoose.connection.name);
|
||||
console.log('URI used:', uri);
|
||||
|
||||
const collections = await proxyMongoose.connection.db.listCollections().toArray();
|
||||
console.log('Collections list:', collections.map(c => c.name));
|
||||
|
||||
await proxyMongoose.disconnect();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,33 +0,0 @@
|
||||
module.paths.unshift('c:\\Users\\demo\\Downloads\\Deep Package Inspection\\node_modules');
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = { host: '103.185.47.52', port: 2222, username: 'adminbackend', password: 'htEo7x6LsBQiEHHH', readyTimeout: 60000 };
|
||||
|
||||
async function main() {
|
||||
const conn = new Client();
|
||||
await new Promise((resolve, reject) => {
|
||||
conn.on('ready', resolve).on('error', reject).connect(SSH);
|
||||
});
|
||||
console.log('SSH connected.');
|
||||
|
||||
const runCmd = (cmd) => {
|
||||
return new Promise((resolve) => {
|
||||
conn.exec(cmd, (err, stream) => {
|
||||
if (err) { resolve(`Err: ${err.message}`); return; }
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => resolve(out.trim()));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const lsFonts = await runCmd('ls -la /home/adminbackend/web/demoplace.my.id/public_html/.next/standalone/public/fonts || echo "No fonts folder"');
|
||||
console.log('=== STANDALONE FONTS DIR ===\n', lsFonts);
|
||||
|
||||
const lsPublicFonts = await runCmd('ls -la /home/adminbackend/web/demoplace.my.id/public_html/public/fonts || echo "No public fonts folder"');
|
||||
console.log('=== SOURCE PUBLIC FONTS DIR ===\n', lsPublicFonts);
|
||||
|
||||
conn.end();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,22 +0,0 @@
|
||||
// test/check-ip-mongo.js
|
||||
const { MongoClient } = require('mongodb');
|
||||
|
||||
const URI = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/backone_dpi';
|
||||
|
||||
async function main() {
|
||||
console.log('Connecting to MongoDB via IP 103.80.237.29...');
|
||||
const client = new MongoClient(URI, { serverSelectionTimeoutMS: 5000 });
|
||||
try {
|
||||
await client.connect();
|
||||
console.log('✓ Successfully connected to MongoDB via IP!');
|
||||
const db = client.db('backone_dpi');
|
||||
const cols = await db.listCollections().toArray();
|
||||
console.log('Collections:', cols.map(c => c.name));
|
||||
} catch (err) {
|
||||
console.error('✗ Connection failed:', err.message);
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -1,20 +0,0 @@
|
||||
require('dotenv').config({ path: './.env.local' });
|
||||
const mongoose = require('mongoose');
|
||||
const { LookupApp } = require('../proxy/models/Schemas');
|
||||
|
||||
async function main() {
|
||||
const uri = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/backone_dpi';
|
||||
console.log('Using URI from env:', uri);
|
||||
await mongoose.connect(uri);
|
||||
console.log('Connected to:', mongoose.connection.name, 'on host:', mongoose.connection.host);
|
||||
|
||||
const count = await LookupApp.countDocuments({});
|
||||
console.log('LookupApp model count:', count);
|
||||
|
||||
const rawCount = await mongoose.connection.db.collection('lookupapps').countDocuments({});
|
||||
console.log('Raw collection count:', rawCount);
|
||||
|
||||
await mongoose.disconnect();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,11 +0,0 @@
|
||||
// test/check-logo-size.js
|
||||
const axios = require('axios');
|
||||
|
||||
async function main() {
|
||||
const url = 'https://demoplace.my.id/nexus-logo.png';
|
||||
const res = await axios.head(url);
|
||||
console.log('Remote nexus-logo.png content-length:', res.headers['content-length']);
|
||||
console.log('Remote nexus-logo.png content-type:', res.headers['content-type']);
|
||||
}
|
||||
|
||||
main().catch(err => console.error(err.message));
|
||||
@@ -1,22 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
conn.exec("/home/adminbackend/.npm-global/bin/pm2 show backone-frontend", (err, stream) => {
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => {
|
||||
console.log('--- PM2 SHOW FRONTEND ---');
|
||||
console.log(out);
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).connect(SSH);
|
||||
@@ -1,22 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
conn.exec("/home/adminbackend/.npm-global/bin/pm2 status; ps -ef | grep node", (err, stream) => {
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => {
|
||||
console.log('--- PM2 & PROCESSES ---');
|
||||
console.log(out);
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).connect(SSH);
|
||||
@@ -1,23 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
console.log('Querying remote Nginx config and PM2 details...');
|
||||
conn.exec("cat /etc/nginx/conf.d/*.conf /etc/nginx/sites-enabled/* /etc/nginx/nginx.conf 2>/dev/null | grep -i -A 10 -B 2 'demoplace.my.id'; /home/adminbackend/.npm-global/bin/pm2 env 2", (err, stream) => {
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => {
|
||||
console.log('--- REMOTE NGINX & PM2 ENV ---');
|
||||
console.log(out);
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).connect(SSH);
|
||||
@@ -1,23 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
console.log('Checking PM2 status and errors...');
|
||||
conn.exec("/home/adminbackend/.npm-global/bin/pm2 list; tail -n 50 /home/adminbackend/web/demoplace.my.id/public_html/logs/frontend-error.log", (err, stream) => {
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => {
|
||||
console.log('--- PM2 STATUS & FRONTEND ERRORS ---');
|
||||
console.log(out);
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).connect(SSH);
|
||||
@@ -1,33 +0,0 @@
|
||||
module.paths.unshift('c:\\Users\\demo\\Downloads\\Deep Package Inspection\\node_modules');
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = { host: '103.185.47.52', port: 2222, username: 'adminbackend', password: 'htEo7x6LsBQiEHHH', readyTimeout: 60000 };
|
||||
|
||||
async function main() {
|
||||
const conn = new Client();
|
||||
await new Promise((resolve, reject) => {
|
||||
conn.on('ready', resolve).on('error', reject).connect(SSH);
|
||||
});
|
||||
console.log('SSH connected.');
|
||||
|
||||
const runCmd = (cmd) => {
|
||||
return new Promise((resolve) => {
|
||||
conn.exec(cmd, (err, stream) => {
|
||||
if (err) { resolve(`Err: ${err.message}`); return; }
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.stderr.on('data', d => out += `[stderr] ${d}`);
|
||||
stream.on('close', () => resolve(out.trim()));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const remoteNodeCmd = `const mongoose = require('/home/adminbackend/web/demoplace.my.id/public_html/proxy/node_modules/mongoose'); mongoose.connect('mongodb://127.0.0.1:27017/backone_dpi').then(() => mongoose.connection.db.collection('lookupapps').countDocuments()).then(c => { console.log('COUNT:', c); process.exit(0); }).catch(e => { console.error(e); process.exit(1); })`;
|
||||
|
||||
const countRes = await runCmd(`node -e ${JSON.stringify(remoteNodeCmd)}`);
|
||||
console.log('=== REMOTE LOOKUP COUNT ===\n', countRes);
|
||||
|
||||
conn.end();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,27 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
conn.exec('cat /home/adminbackend/web/demoplace.my.id/public_html/proxy/.env /home/adminbackend/web/demoplace.my.id/public_html/backend/.env /home/adminbackend/web/demoplace.my.id/public_html/.env.production', (err, stream) => {
|
||||
if (err) {
|
||||
console.error(err);
|
||||
conn.end();
|
||||
return;
|
||||
}
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => {
|
||||
console.log('--- REMOTE ENVS ---');
|
||||
console.log(out);
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).on('error', console.error).connect(SSH);
|
||||
@@ -1,22 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
conn.exec("find /home/adminbackend/web/demoplace.my.id/public_html/.next/standalone -path '*agents*' -ls", (err, stream) => {
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => {
|
||||
console.log('--- REMOTE NEXT AGENTS FILES ---');
|
||||
console.log(out);
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).connect(SSH);
|
||||
@@ -1,22 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
conn.exec("ls -ld /home/adminbackend/web/demoplace.my.id/public_html/.next; ls -l /home/adminbackend/web/demoplace.my.id/public_html/.next/standalone/server.js", (err, stream) => {
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => {
|
||||
console.log('--- REMOTE NEXT DATE ---');
|
||||
console.log(out);
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).connect(SSH);
|
||||
@@ -1,33 +0,0 @@
|
||||
module.paths.unshift('c:\\Users\\demo\\Downloads\\Deep Package Inspection\\node_modules');
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = { host: '103.185.47.52', port: 2222, username: 'adminbackend', password: 'htEo7x6LsBQiEHHH', readyTimeout: 60000 };
|
||||
|
||||
async function main() {
|
||||
const conn = new Client();
|
||||
await new Promise((resolve, reject) => {
|
||||
conn.on('ready', resolve).on('error', reject).connect(SSH);
|
||||
});
|
||||
console.log('SSH connected.');
|
||||
|
||||
const runCmd = (cmd) => {
|
||||
return new Promise((resolve) => {
|
||||
conn.exec(cmd, (err, stream) => {
|
||||
if (err) { resolve(`Err: ${err.message}`); return; }
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => resolve(out.trim()));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const lsStandalone = await runCmd('ls -la /home/adminbackend/web/demoplace.my.id/public_html/.next/standalone');
|
||||
console.log('=== STANDALONE DIR ===\n', lsStandalone);
|
||||
|
||||
const lsStandalonePublic = await runCmd('ls -la /home/adminbackend/web/demoplace.my.id/public_html/.next/standalone/public || echo "No public folder in standalone"');
|
||||
console.log('=== STANDALONE PUBLIC DIR ===\n', lsStandalonePublic);
|
||||
|
||||
conn.end();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,30 +0,0 @@
|
||||
// test/check_local_db.js
|
||||
const { MongoClient } = require('mongodb');
|
||||
|
||||
const LOCAL_URI = 'mongodb://127.0.0.1:27017';
|
||||
const DB_NAME = 'backone_dpi';
|
||||
|
||||
async function main() {
|
||||
const client = new MongoClient(LOCAL_URI, { serverSelectionTimeoutMS: 2000 });
|
||||
try {
|
||||
await client.connect();
|
||||
console.log("✓ Connected to local MongoDB successfully!");
|
||||
const db = client.db(DB_NAME);
|
||||
const collections = await db.listCollections().toArray();
|
||||
console.log("Collections in local database:", collections.map(c => c.name));
|
||||
|
||||
if (collections.some(c => c.name === 'users')) {
|
||||
const users = await db.collection('users').find({}).toArray();
|
||||
console.log(`Users in local database (${users.length}):`);
|
||||
users.forEach(u => console.log(`- Username: ${u.username}, Role: ${u.role}, Email: ${u.email || 'N/A'}`));
|
||||
} else {
|
||||
console.log("No 'users' collection locally.");
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("✗ Local MongoDB connection failed:", err.message);
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -1,27 +0,0 @@
|
||||
// test/check_pm2_restarts.js
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const sshConfig = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH'
|
||||
};
|
||||
|
||||
async function main() {
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
conn.exec('. ~/.nvm/nvm.sh && nvm use 20 && npx pm2 list', (err, stream) => {
|
||||
if (err) throw err;
|
||||
let out = '';
|
||||
stream.on('close', () => {
|
||||
conn.end();
|
||||
console.log(out);
|
||||
}).on('data', (data) => {
|
||||
out += data;
|
||||
});
|
||||
});
|
||||
}).connect(sshConfig);
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -1,30 +0,0 @@
|
||||
// test/check_prod_after_migration.js
|
||||
const { MongoClient } = require('mongodb');
|
||||
|
||||
const REMOTE_URI = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/backone_dpi';
|
||||
const DB_NAME = 'backone_dpi';
|
||||
|
||||
async function main() {
|
||||
const client = new MongoClient(REMOTE_URI, { serverSelectionTimeoutMS: 5000 });
|
||||
try {
|
||||
await client.connect();
|
||||
console.log("✓ Connected to production MongoDB successfully!");
|
||||
const db = client.db(DB_NAME);
|
||||
const collections = await db.listCollections().toArray();
|
||||
console.log("Collections in production database:", collections.map(c => c.name));
|
||||
|
||||
const users = await db.collection('users').find({}).toArray();
|
||||
console.log(`Users in production MongoDB (${users.length}):`);
|
||||
users.forEach(u => console.log(`- Username: ${u.username}, Role: ${u.role}, Site UUID: ${u.site_uuid || 'N/A'}`));
|
||||
|
||||
const configCount = await db.collection('tenantconfigs').countDocuments();
|
||||
const locCount = await db.collection('customagentlocations').countDocuments();
|
||||
console.log(`\nConfig entries: ${configCount}, Custom location entries: ${locCount}`);
|
||||
} catch (err) {
|
||||
console.error("✗ Production MongoDB connection failed:", err.message);
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -1,90 +0,0 @@
|
||||
// test/check_remote_env.js
|
||||
// Fix 502: Write Nginx custom config to proxy directly to Next.js port 3000
|
||||
'use strict';
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const sshConfig = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
function runSSHCommand(conn, cmd) {
|
||||
return new Promise((resolve, reject) => {
|
||||
conn.exec(cmd, (err, stream) => {
|
||||
if (err) return reject(err);
|
||||
let out = '';
|
||||
stream.on('close', () => resolve(out))
|
||||
.on('data', d => { out += d; process.stdout.write(d.toString()); })
|
||||
.stderr.on('data', d => { out += d; process.stdout.write(d.toString()); });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const conn = new Client();
|
||||
await new Promise((resolve, reject) => {
|
||||
conn.on('ready', resolve).on('error', reject).connect(sshConfig);
|
||||
});
|
||||
console.log('[SSH] Connected!\n');
|
||||
|
||||
const CONF = '/home/adminbackend/conf/web/demoplace.my.id';
|
||||
|
||||
// The Nginx config includes nginx.conf_custom and nginx.ssl.conf_custom
|
||||
// We override the location / block to proxy directly to Next.js port 3000
|
||||
const httpCustom = [
|
||||
'# BackOne DPI — Direct proxy to Next.js',
|
||||
'location / {',
|
||||
' proxy_pass http://127.0.0.1:3000;',
|
||||
' proxy_http_version 1.1;',
|
||||
' proxy_set_header Upgrade $http_upgrade;',
|
||||
' proxy_set_header Connection "upgrade";',
|
||||
' proxy_set_header Host $host;',
|
||||
' proxy_set_header X-Real-IP $remote_addr;',
|
||||
' proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;',
|
||||
' proxy_set_header X-Forwarded-Proto $scheme;',
|
||||
' proxy_read_timeout 86400;',
|
||||
'}',
|
||||
].join('\n');
|
||||
|
||||
const sslCustom = [
|
||||
'# BackOne DPI — Direct SSL proxy to Next.js',
|
||||
'location / {',
|
||||
' proxy_pass http://127.0.0.1:3000;',
|
||||
' proxy_http_version 1.1;',
|
||||
' proxy_set_header Upgrade $http_upgrade;',
|
||||
' proxy_set_header Connection "upgrade";',
|
||||
' proxy_set_header Host $host;',
|
||||
' proxy_set_header X-Real-IP $remote_addr;',
|
||||
' proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;',
|
||||
' proxy_set_header X-Forwarded-Proto https;',
|
||||
' proxy_read_timeout 86400;',
|
||||
'}',
|
||||
].join('\n');
|
||||
|
||||
const commands = [
|
||||
// Write HTTP custom config
|
||||
`printf '%s\n' ${JSON.stringify(httpCustom)} > ${CONF}/nginx.conf_custom && echo "[OK] HTTP custom config written"`,
|
||||
// Write SSL custom config
|
||||
`printf '%s\n' ${JSON.stringify(sslCustom)} > ${CONF}/nginx.ssl.conf_custom && echo "[OK] SSL custom config written"`,
|
||||
// Verify files
|
||||
`echo "=== HTTP CUSTOM ===" && cat ${CONF}/nginx.conf_custom`,
|
||||
`echo "=== SSL CUSTOM ===" && cat ${CONF}/nginx.ssl.conf_custom`,
|
||||
// Reload Nginx via Hestia
|
||||
`echo "=== RELOADING ===" && sudo /usr/local/hestia/bin/v-restart-web 2>&1 | tail -5 || nginx -s reload 2>&1 | tail -5 || echo "Reload attempt done"`,
|
||||
// Test after reload
|
||||
`sleep 6 && echo "=== DOMAIN TEST ===" && curl -sk -o /dev/null -w "HTTPS Status: %{http_code}" https://demoplace.my.id/login`,
|
||||
];
|
||||
|
||||
for (const cmd of commands) {
|
||||
console.log(`\n$ ${cmd.substring(0, 100)}${cmd.length > 100 ? '...' : ''}`);
|
||||
await runSSHCommand(conn, cmd);
|
||||
}
|
||||
|
||||
conn.end();
|
||||
console.log('\n\n✅ Selesai! Cek https://demoplace.my.id/login di browser.\n');
|
||||
}
|
||||
|
||||
main().catch(err => { console.error('[FATAL]', err.message); process.exit(1); });
|
||||
@@ -1,23 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
console.log('Cleaning up backslash files/folders on remote server...');
|
||||
conn.exec("find /home/adminbackend/web/demoplace.my.id/public_html -name '*\\\\*' -depth -exec rm -rf {} \\; -print", (err, stream) => {
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => {
|
||||
console.log('--- CLEANED UP REMOTE FILES ---');
|
||||
console.log(out);
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).connect(SSH);
|
||||
@@ -1,32 +0,0 @@
|
||||
const mongoose = require('../backend/node_modules/mongoose');
|
||||
const dotenv = require('../backend/node_modules/dotenv');
|
||||
const path = require('path');
|
||||
|
||||
// Load environment variables from .env.local
|
||||
dotenv.config({ path: path.join(__dirname, '../.env.local') });
|
||||
|
||||
const mongoUri = process.env.MONGO_URI || 'mongodb://127.0.0.1:27017/backone_dpi';
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
console.log(`Connecting to: ${mongoUri}`);
|
||||
await mongoose.connect(mongoUri);
|
||||
console.log('Connected! Deleting all demo user accounts (all except admin, siab, and nexus)...');
|
||||
|
||||
const db = mongoose.connection.db;
|
||||
const usernamesToKeep = ['admin', 'siab', 'nexus'];
|
||||
|
||||
const res = await db.collection('users').deleteMany({
|
||||
username: { $nin: usernamesToKeep }
|
||||
});
|
||||
|
||||
console.log(`Deleted ${res.deletedCount} demo users.`);
|
||||
await mongoose.disconnect();
|
||||
console.log('Done!');
|
||||
} catch (err) {
|
||||
console.error('Error deleting users:', err);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -1,32 +0,0 @@
|
||||
const mongoose = require('../backend/node_modules/mongoose');
|
||||
const dotenv = require('../backend/node_modules/dotenv');
|
||||
const path = require('path');
|
||||
|
||||
// Load environment variables from .env.local
|
||||
dotenv.config({ path: path.join(__dirname, '../.env.local') });
|
||||
|
||||
const mongoUri = process.env.MONGO_URI || 'mongodb://127.0.0.1:27017/backone_dpi';
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
console.log(`Connecting to: ${mongoUri}`);
|
||||
await mongoose.connect(mongoUri);
|
||||
console.log('Connected! Deleting superadmin external accounts...');
|
||||
|
||||
const db = mongoose.connection.db;
|
||||
const usernamesToDelete = ['super_analyst', 'super_engineer', 'sulist', 'suner'];
|
||||
|
||||
const res = await db.collection('users').deleteMany({
|
||||
username: { $in: usernamesToDelete }
|
||||
});
|
||||
|
||||
console.log(`Deleted ${res.deletedCount} users:`, usernamesToDelete);
|
||||
await mongoose.disconnect();
|
||||
console.log('Done!');
|
||||
} catch (err) {
|
||||
console.error('Error deleting users:', err);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -1,30 +0,0 @@
|
||||
module.paths.unshift('c:\\Users\\demo\\Downloads\\Deep Package Inspection\\node_modules');
|
||||
const { Client } = require('ssh2');
|
||||
const fs = require('fs');
|
||||
|
||||
const SSH = { host: '103.185.47.52', port: 2222, username: 'adminbackend', password: 'htEo7x6LsBQiEHHH', readyTimeout: 60000 };
|
||||
const REMOTE_PATH = '/home/adminbackend/web/demoplace.my.id/public_html/.env.production';
|
||||
const LOCAL_PATH = 'c:\\Users\\demo\\Downloads\\Deep Package Inspection\\.env.production';
|
||||
|
||||
async function main() {
|
||||
const conn = new Client();
|
||||
await new Promise((resolve, reject) => {
|
||||
conn.on('ready', resolve).on('error', reject).connect(SSH);
|
||||
});
|
||||
console.log('SSH connected. Downloading .env.production...');
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
conn.sftp((err, sftp) => {
|
||||
if (err) return reject(err);
|
||||
sftp.fastGet(REMOTE_PATH, LOCAL_PATH, {}, (err2) => {
|
||||
if (err2) return reject(err2);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
console.log('Downloaded successfully to:', LOCAL_PATH);
|
||||
conn.end();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,83 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const REMOTE_ROOT = '/home/adminbackend/web/demoplace.my.id/public_html';
|
||||
const LOCAL_ROOT = path.join(__dirname, '..');
|
||||
|
||||
const filesToDownload = [
|
||||
'src/app/(dashboard)/agents/page.tsx',
|
||||
'src/app/(dashboard)/apps/page.tsx',
|
||||
'src/app/(dashboard)/devices/page.tsx',
|
||||
'src/app/(dashboard)/dns/page.tsx',
|
||||
'src/app/(dashboard)/dpi-analytics/page.tsx',
|
||||
'src/app/(dashboard)/events/page.tsx',
|
||||
'src/app/(dashboard)/flows/page.tsx',
|
||||
'src/app/(dashboard)/geography/page.tsx',
|
||||
'src/app/(dashboard)/intelligence/page.tsx',
|
||||
'src/app/(dashboard)/lookup/page.tsx',
|
||||
'src/app/(dashboard)/network-infrastructure/page.tsx',
|
||||
'src/app/(dashboard)/network-intelligence/page.tsx',
|
||||
'src/app/(dashboard)/page.tsx',
|
||||
'src/app/(dashboard)/security-audit/page.tsx',
|
||||
'src/app/(dashboard)/threats/page.tsx',
|
||||
'src/components/admin/ExternalAccountModal.tsx',
|
||||
'src/components/layout/Sidebar.tsx',
|
||||
'src/components/layout/SidebarData.ts',
|
||||
'src/components/ui/SafeImage.tsx',
|
||||
'src/lib/actions/agents.ts',
|
||||
'src/lib/admin-api.ts',
|
||||
'package.json'
|
||||
];
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
console.log('✓ SSH Connection ready for SFTP...');
|
||||
conn.sftp((err, sftp) => {
|
||||
if (err) {
|
||||
console.error('SFTP Error:', err.message);
|
||||
conn.end();
|
||||
return;
|
||||
}
|
||||
|
||||
let downloadedCount = 0;
|
||||
let failedCount = 0;
|
||||
|
||||
filesToDownload.forEach((relPath) => {
|
||||
const remotePath = `${REMOTE_ROOT}/${relPath}`;
|
||||
const localPath = path.join(LOCAL_ROOT, relPath);
|
||||
|
||||
// Ensure target directory exists
|
||||
const localDir = path.dirname(localPath);
|
||||
if (!fs.existsSync(localDir)) {
|
||||
fs.mkdirSync(localDir, { recursive: true });
|
||||
}
|
||||
|
||||
console.log(`Downloading: ${relPath} ...`);
|
||||
sftp.fastGet(remotePath, localPath, (sftpErr) => {
|
||||
if (sftpErr) {
|
||||
console.error(`✗ Failed to download ${relPath}:`, sftpErr.message);
|
||||
failedCount++;
|
||||
} else {
|
||||
console.log(`✓ Downloaded ${relPath}`);
|
||||
downloadedCount++;
|
||||
}
|
||||
|
||||
if (downloadedCount + failedCount === filesToDownload.length) {
|
||||
console.log(`\n=========================================`);
|
||||
console.log(` DOWNLOAD COMPLETED: ${downloadedCount} Succeeded, ${failedCount} Failed.`);
|
||||
console.log(`=========================================\n`);
|
||||
conn.end();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}).on('error', console.error).connect(SSH);
|
||||
@@ -1,78 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const SSH_CONFIG = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH'
|
||||
};
|
||||
|
||||
const remoteDir = '/home/adminbackend/web/demoplace.my.id/public_html/api/uploads';
|
||||
const localDir = path.join(__dirname, '../public/api/uploads');
|
||||
|
||||
// Ensure local directory exists
|
||||
if (!fs.existsSync(localDir)) {
|
||||
fs.mkdirSync(localDir, { recursive: true });
|
||||
}
|
||||
|
||||
console.log('Connecting to SSH...');
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
console.log('SSH Connection ready. Starting SFTP...');
|
||||
conn.sftp(async (err, sftp) => {
|
||||
if (err) {
|
||||
console.error('SFTP Error:', err.message);
|
||||
conn.end();
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('Listing remote uploads directory:', remoteDir);
|
||||
sftp.readdir(remoteDir, async (err, list) => {
|
||||
if (err) {
|
||||
console.error('Readdir Error:', err.message);
|
||||
conn.end();
|
||||
return;
|
||||
}
|
||||
|
||||
const files = list.filter(item => item.attrs.isFile());
|
||||
console.log(`Found ${files.length} upload files on remote server.`);
|
||||
|
||||
if (files.length === 0) {
|
||||
conn.end();
|
||||
return;
|
||||
}
|
||||
|
||||
// Download files sequentially using a helper function
|
||||
async function downloadFile(index) {
|
||||
if (index >= files.length) {
|
||||
console.log('\n=========================================');
|
||||
console.log(' ALL UPLOADS DOWNLOAD COMPLETED.');
|
||||
console.log('=========================================');
|
||||
conn.end();
|
||||
return;
|
||||
}
|
||||
|
||||
const name = files[index].filename;
|
||||
const remoteFile = path.posix.join(remoteDir, name);
|
||||
const localFile = path.join(localDir, name);
|
||||
|
||||
console.log(`[${index + 1}/${files.length}] Downloading: ${name} ...`);
|
||||
|
||||
sftp.fastGet(remoteFile, localFile, {}, (err) => {
|
||||
if (err) {
|
||||
console.error(`Failed to download ${name}:`, err.message);
|
||||
} else {
|
||||
console.log(`✓ Completed ${name}`);
|
||||
}
|
||||
// Proceed to next file
|
||||
setTimeout(() => downloadFile(index + 1), 50);
|
||||
});
|
||||
}
|
||||
|
||||
// Start the sequential download
|
||||
await downloadFile(0);
|
||||
});
|
||||
});
|
||||
}).connect(SSH_CONFIG);
|
||||
@@ -1,71 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const SSH_CONFIG = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH'
|
||||
};
|
||||
|
||||
const remoteDir = '/home/adminbackend/web/demoplace.my.id/public_html/api/uploads';
|
||||
const localDir = path.join(__dirname, '../public/api/uploads');
|
||||
|
||||
// Ensure local directory exists
|
||||
if (!fs.existsSync(localDir)) {
|
||||
fs.mkdirSync(localDir, { recursive: true });
|
||||
}
|
||||
|
||||
console.log('Connecting to SSH...');
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
console.log('SSH Connection ready. Starting SFTP...');
|
||||
conn.sftp((err, sftp) => {
|
||||
if (err) {
|
||||
console.error('SFTP Error:', err.message);
|
||||
conn.end();
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('Listing remote uploads directory:', remoteDir);
|
||||
sftp.readdir(remoteDir, (err, list) => {
|
||||
if (err) {
|
||||
console.error('Readdir Error:', err.message);
|
||||
conn.end();
|
||||
return;
|
||||
}
|
||||
|
||||
const files = list.filter(item => item.attrs.isFile());
|
||||
console.log(`Found ${files.length} upload files on remote server.`);
|
||||
|
||||
if (files.length === 0) {
|
||||
conn.end();
|
||||
return;
|
||||
}
|
||||
|
||||
let downloaded = 0;
|
||||
files.forEach(fileInfo => {
|
||||
const name = fileInfo.filename;
|
||||
const remoteFile = path.posix.join(remoteDir, name);
|
||||
const localFile = path.join(localDir, name);
|
||||
|
||||
console.log(`Downloading: ${name} ...`);
|
||||
sftp.fastGet(remoteFile, localFile, {}, (err) => {
|
||||
if (err) {
|
||||
console.error(`Failed to download ${name}:`, err.message);
|
||||
} else {
|
||||
console.log(`✓ Downloaded ${name}`);
|
||||
}
|
||||
downloaded++;
|
||||
if (downloaded === files.length) {
|
||||
console.log('\n=========================================');
|
||||
console.log(' ALL UPLOADS DOWNLOAD COMPLETED.');
|
||||
console.log('=========================================');
|
||||
conn.end();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
}).connect(SSH_CONFIG);
|
||||
@@ -1,27 +0,0 @@
|
||||
const axios = require('axios');
|
||||
|
||||
async function main() {
|
||||
const loginRes = await axios.post('https://demoplace.my.id/api/auth/login', {
|
||||
username: 'admin',
|
||||
password: 'admin'
|
||||
});
|
||||
|
||||
const cookie = loginRes.headers['set-cookie'];
|
||||
const pageRes = await axios.get('https://demoplace.my.id/agents', {
|
||||
headers: {
|
||||
Cookie: cookie ? cookie.join('; ') : ''
|
||||
}
|
||||
});
|
||||
|
||||
const html = pageRes.data;
|
||||
|
||||
console.log("=== HEADINGS ===");
|
||||
const headings = html.match(/<h[1-6][^>]*>[\s\S]*?<\/h[1-6]>/gi) || [];
|
||||
headings.forEach(h => console.log(h.replace(/<[^>]+>/g, '').trim()));
|
||||
|
||||
console.log("=== CARD TITLES OR TABLE TITLES ===");
|
||||
const textMatches = html.match(/[^>]{5,100}(?:External Accounts|Agents|Inventory|Tenant)[^<]{5,100}/gi) || [];
|
||||
textMatches.slice(0, 30).forEach(t => console.log(t.replace(/<[^>]+>/g, '').trim()));
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,90 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = {
|
||||
host: process.env.SSH_HOST || '127.0.0.1',
|
||||
port: parseInt(process.env.SSH_PORT || '2222'),
|
||||
username: process.env.SSH_USER || 'adminbackend',
|
||||
password: process.env.SSH_PASSWORD || '',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const remoteJs = `
|
||||
const mongoose = require('/home/adminbackend/web/demoplace.my.id/public_html/backend/node_modules/mongoose');
|
||||
|
||||
async function main() {
|
||||
console.log('Remote: Requiring mongoose succeeded. Connecting...');
|
||||
const URI = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/backone_dpi';
|
||||
try {
|
||||
await mongoose.connect(URI, {
|
||||
serverSelectionTimeoutMS: 10000,
|
||||
connectTimeoutMS: 10000,
|
||||
});
|
||||
console.log('Remote: Connected to DB.');
|
||||
const db = mongoose.connection.db;
|
||||
const collections = await db.listCollections().toArray();
|
||||
console.log('Remote: Listed collections.');
|
||||
const result = {};
|
||||
for (const col of collections) {
|
||||
const name = col.name;
|
||||
console.log('Remote: Querying collection ' + name);
|
||||
const count = await db.collection(name).countDocuments({});
|
||||
if (['users', 'tenantconfigs', 'customagentlocations', 'blacklistrules', 'summaries'].includes(name)) {
|
||||
const docs = await db.collection(name).find({}).toArray();
|
||||
result[name] = { count, docs };
|
||||
} else {
|
||||
result[name] = { count };
|
||||
}
|
||||
}
|
||||
console.log('--- JSON_START ---');
|
||||
console.log(JSON.stringify(result));
|
||||
console.log('--- JSON_END ---');
|
||||
} catch (err) {
|
||||
console.error('Remote Error:', err.message);
|
||||
} finally {
|
||||
await mongoose.disconnect();
|
||||
console.log('Remote: Mongoose disconnected.');
|
||||
}
|
||||
}
|
||||
main();
|
||||
`;
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
const b64 = Buffer.from(remoteJs).toString('base64');
|
||||
conn.exec(`echo "${b64}" | base64 -d | node`, (err, stream) => {
|
||||
if (err) {
|
||||
console.error(err);
|
||||
conn.end();
|
||||
return;
|
||||
}
|
||||
let out = '';
|
||||
stream.on('data', d => {
|
||||
const chunk = d.toString();
|
||||
process.stdout.write(chunk);
|
||||
out += chunk;
|
||||
});
|
||||
stream.stderr.on('data', d => {
|
||||
process.stderr.write(d.toString());
|
||||
});
|
||||
stream.on('close', () => {
|
||||
const startIdx = out.indexOf('--- JSON_START ---');
|
||||
const endIdx = out.indexOf('--- JSON_END ---');
|
||||
if (startIdx !== -1 && endIdx !== -1) {
|
||||
const jsonStr = out.substring(startIdx + '--- JSON_START ---'.length, endIdx).trim();
|
||||
try {
|
||||
const parsed = JSON.parse(jsonStr);
|
||||
console.log('\n--- REMOTE COLLECTIONS INFO ---');
|
||||
for (const [name, info] of Object.entries(parsed)) {
|
||||
console.log(`- ${name}: ${info.count} documents`);
|
||||
}
|
||||
const fs = require('fs');
|
||||
fs.writeFileSync('C:\\Users\\demo\\.gemini\\antigravity-ide\\scratch\\remote_db_dump.json', jsonStr);
|
||||
console.log('\n✓ Saved full DB dump locally to scratch/remote_db_dump.json');
|
||||
} catch (e) {
|
||||
console.error('\nFailed to parse JSON segment:', e.message);
|
||||
}
|
||||
}
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).on('error', console.error).connect(SSH);
|
||||
@@ -1,26 +0,0 @@
|
||||
const axios = require('axios');
|
||||
|
||||
async function main() {
|
||||
console.log('Logging in to remote server...');
|
||||
const loginRes = await axios.post('https://demoplace.my.id/api/auth/login', {
|
||||
username: 'nexus',
|
||||
password: 'nexus'
|
||||
});
|
||||
|
||||
const cookie = loginRes.headers['set-cookie'];
|
||||
console.log('Login successful. Cookies:', cookie);
|
||||
|
||||
console.log('Fetching / (Overview page) with cookie...');
|
||||
const pageRes = await axios.get('https://demoplace.my.id/', {
|
||||
headers: {
|
||||
Cookie: cookie ? cookie.join('; ') : ''
|
||||
}
|
||||
});
|
||||
|
||||
console.log('Page HTTP Status:', pageRes.status);
|
||||
console.log('Page HTML length:', pageRes.data.length);
|
||||
console.log('HTML snippet (first 500 chars):');
|
||||
console.log(pageRes.data.substring(0, 500));
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,25 +0,0 @@
|
||||
const axios = require('axios');
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
console.log('Fetching https://demoplace.my.id/ ...');
|
||||
const res1 = await axios.get('https://demoplace.my.id/', { maxRedirects: 0, validateStatus: () => true });
|
||||
console.log('Status /:', res1.status);
|
||||
console.log('Headers /:', res1.headers);
|
||||
console.log('Body snippet /:', res1.data.substring(0, 500));
|
||||
} catch (err) {
|
||||
console.error('Error /:', err.message);
|
||||
}
|
||||
|
||||
try {
|
||||
console.log('\nFetching https://demoplace.my.id/login ...');
|
||||
const res2 = await axios.get('https://demoplace.my.id/login', { maxRedirects: 0, validateStatus: () => true });
|
||||
console.log('Status /login:', res2.status);
|
||||
console.log('Headers /login:', res2.headers);
|
||||
console.log('Body snippet /login:', res2.data.substring(0, 500));
|
||||
} catch (err) {
|
||||
console.error('Error /login:', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,39 +0,0 @@
|
||||
const axios = require('axios');
|
||||
|
||||
async function main() {
|
||||
console.log('Logging in to remote server...');
|
||||
const loginRes = await axios.post('https://demoplace.my.id/api/auth/login', {
|
||||
username: 'admin',
|
||||
password: 'admin'
|
||||
});
|
||||
|
||||
const cookie = loginRes.headers['set-cookie'];
|
||||
console.log('Login successful. Cookies:', cookie);
|
||||
|
||||
console.log('Fetching /agents page...');
|
||||
const pageRes = await axios.get('https://demoplace.my.id/agents', {
|
||||
headers: {
|
||||
Cookie: cookie ? cookie.join('; ') : ''
|
||||
}
|
||||
});
|
||||
|
||||
const html = pageRes.data;
|
||||
console.log('Page HTML length:', html.length);
|
||||
|
||||
const hasSuperadminTable = html.includes('Superadmin (BackOne) External Accounts');
|
||||
const hasInventoryTable = html.includes('External Accounts Inventory');
|
||||
console.log('Contains Superadmin table:', hasSuperadminTable);
|
||||
console.log('Contains Inventory table:', hasInventoryTable);
|
||||
|
||||
// Find where table title is mentioned
|
||||
const idx1 = html.indexOf('Superadmin (BackOne)');
|
||||
if (idx1 !== -1) {
|
||||
console.log('Snippet around Superadmin:', html.substring(idx1 - 100, idx1 + 200));
|
||||
}
|
||||
const idx2 = html.indexOf('External Accounts Inventory');
|
||||
if (idx2 !== -1) {
|
||||
console.log('Snippet around Inventory:', html.substring(idx2 - 100, idx2 + 200));
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,30 +0,0 @@
|
||||
// test/fetch-sidebar-logo.js
|
||||
const axios = require('axios');
|
||||
|
||||
async function main() {
|
||||
console.log('Logging in as nexus...');
|
||||
const loginRes = await axios.post('https://demoplace.my.id/api/auth/login', {
|
||||
username: 'nexus',
|
||||
password: 'nexus'
|
||||
});
|
||||
|
||||
const cookie = loginRes.headers['set-cookie'];
|
||||
const headers = { Cookie: cookie ? cookie.join('; ') : '' };
|
||||
|
||||
console.log('Fetching overview page...');
|
||||
const pageRes = await axios.get('https://demoplace.my.id/', { headers });
|
||||
|
||||
const html = pageRes.data;
|
||||
|
||||
// Find all img tags using a regex
|
||||
const imgRegex = /<img[^>]+src=["']([^"']+)["']/g;
|
||||
let match;
|
||||
console.log('Found image tags in HTML:');
|
||||
while ((match = imgRegex.exec(html)) !== null) {
|
||||
console.log(' - src:', match[1]);
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(err => {
|
||||
console.error('Error:', err.message);
|
||||
});
|
||||
@@ -1,148 +0,0 @@
|
||||
// test/final_review.js
|
||||
// Final Review — Verifikasi semua deliverable dari original request
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const ROOT = path.join(__dirname, '..');
|
||||
|
||||
function r(f) { return fs.readFileSync(path.join(ROOT, f), 'utf8'); }
|
||||
|
||||
let ok = 0, fail = 0;
|
||||
function check(label, condition) {
|
||||
const mark = condition ? '✓' : '✗ FAIL';
|
||||
console.log(` ${mark}: ${label}`);
|
||||
condition ? ok++ : fail++;
|
||||
}
|
||||
|
||||
console.log('\n╔══════════════════════════════════════════════════════╗');
|
||||
console.log('║ FINAL REVIEW — Original Request Deliverables ║');
|
||||
console.log('╚══════════════════════════════════════════════════════╝\n');
|
||||
|
||||
const dash = r('backend/routes/dashboard.js') +
|
||||
r('backend/routes/dashboard/helpers.js') +
|
||||
r('backend/routes/dashboard/summary.js') +
|
||||
r('backend/routes/dashboard/apps.js') +
|
||||
r('backend/routes/dashboard/devices.js') +
|
||||
r('backend/routes/dashboard/flows.js') +
|
||||
r('backend/routes/dashboard/threats.js') +
|
||||
r('backend/routes/dashboard/geo.js') +
|
||||
r('backend/routes/dashboard/tls.js') +
|
||||
r('backend/routes/dashboard/telemetry.js') +
|
||||
r('backend/routes/dashboard/events.js') +
|
||||
r('backend/routes/dashboard/agents.js');
|
||||
const auth = r('backend/routes/auth.js');
|
||||
const server = r('backend/server.js');
|
||||
const sched = r('proxy/scheduler.js');
|
||||
const coll = r('proxy/collector.js') + r('proxy/collectorHelperDpi2.js');
|
||||
const compose = r('docker-compose.yml');
|
||||
const proxyIdx = r('proxy/index.js') + (fs.existsSync(path.join(ROOT, 'proxy/routes.js')) ? r('proxy/routes.js') : '');
|
||||
const proxySchema = r('proxy/models/Schemas.js');
|
||||
const pkg = JSON.parse(r('backend/package.json'));
|
||||
const envFileAll = r('.env.local') + (fs.existsSync(path.join(ROOT, '.env.production')) ? r('.env.production') : '');
|
||||
|
||||
// ─── DELIVERABLE 1: Proxy 2 Mode ───────────────────────────────────────────
|
||||
console.log('📦 DELIVERABLE 1: Proxy — 2 Mode Pengambilan Data');
|
||||
check('Mode ALL: collectAllAgents() ada', coll.includes('collectAllAgents'));
|
||||
check('Mode AGENT: collectSpecificAgent() ada', coll.includes('collectSpecificAgent'));
|
||||
check('Scheduler baca PROXY_COLLECT_MODE env', sched.includes('PROXY_COLLECT_MODE'));
|
||||
check('Scheduler baca PROXY_AGENT_UUID env', sched.includes('PROXY_AGENT_UUID'));
|
||||
check('Jika mode=agent → collectSpecificAgent', sched.includes("COLLECT_MODE === 'agent'"));
|
||||
check('Jika mode=all → collectAllAgents', sched.includes('collectAllAgents'));
|
||||
console.log('');
|
||||
|
||||
// ─── DELIVERABLE 2: Data Isolation per Agent UUID ──────────────────────────
|
||||
console.log('📦 DELIVERABLE 2: Isolasi Data per Network Agent UUID di MongoDB');
|
||||
check('Proxy tag dokumen dengan agent_uuid', coll.includes('agent_uuid: agentUuid'));
|
||||
check('Proxy tag dokumen dengan site_uuid', coll.includes('site_uuid'));
|
||||
check('Proxy simpan IP address per agent', coll.includes('ip_address'));
|
||||
check('Proxy simpan MAC address per agent', coll.includes('mac_address'));
|
||||
check('Proxy simpan timestamp per agent', coll.includes('timestamp'));
|
||||
check('Proxy simpan bandwidth per agent', coll.includes('bandwidth_down') || coll.includes('download'));
|
||||
check('Summary schema punya agent_uuid', proxySchema.includes('agent_uuid'));
|
||||
check('Flow schema punya agent_uuid', proxySchema.includes('FlowSchema'));
|
||||
check('Device schema punya mac_address', proxySchema.includes('mac_address'));
|
||||
check('Threat schema ada', proxySchema.includes('ThreatSchema'));
|
||||
console.log('');
|
||||
|
||||
// ─── DELIVERABLE 3: Backend READ-ONLY dari MongoDB ─────────────────────────
|
||||
console.log('📦 DELIVERABLE 3: Backend Hanya Baca MongoDB (bukan tulis/ingestion)');
|
||||
check('server.js tidak ada ingestionService', !server.includes('ingestionService'));
|
||||
check('server.js tidak ada startScheduler', !server.includes('startScheduler'));
|
||||
check('server.js tidak ada import SQLite database.js', !server.includes("'./database'"));
|
||||
check('dashboard.js tidak ada db.getStats SQLite', !dash.includes('db.getStats'));
|
||||
check('dashboard.js tidak ada db.getBandwidthTimeline', !dash.includes('getBandwidthTimeline'));
|
||||
check('dashboard.js tidak ada db.getLatest SQLite', !dash.includes('db.getLatest'));
|
||||
check('auth.js tidak import database.js', !auth.includes("require('../database')"));
|
||||
check('auth.js tidak ada better-sqlite3', !auth.includes('better-sqlite3'));
|
||||
check('package.json tidak ada sqlite3', !pkg.dependencies['sqlite3'] && !pkg.dependencies['better-sqlite3']);
|
||||
console.log('');
|
||||
|
||||
// ─── DELIVERABLE 4: Multi-tenant isolasi per agent ─────────────────────────
|
||||
console.log('📦 DELIVERABLE 4: Multi-Tenant Isolation (Backend filter per agent_uuid)');
|
||||
check('getBaseFilter() helper ada', dash.includes('function getBaseFilter'));
|
||||
check('agent_uuid filter diterapkan jika AGENT_VIEWER', dash.includes('filter.agent_uuid = req.user.agent_uuid'));
|
||||
check('site_uuid filter diterapkan', dash.includes('filter.site_uuid'));
|
||||
check('Semua route aggregate pakai baseFilter/matchBase', (dash.match(/matchBase|getBaseFilter/g) || []).length > 15);
|
||||
check('/agents hanya SUPER_ADMIN', dash.includes('SUPER_ADMIN') || auth.includes('SUPER_ADMIN'));
|
||||
check('SUPER_ADMIN lihat semua data (no agent filter)', dash.includes('AGENT_VIEWER') || auth.includes('AGENT_VIEWER'));
|
||||
check('View-As mode didukung di backend', server.includes('AGENT_VIEWER') || dash.includes('AGENT_VIEWER') || dash.includes('view_as') || dash.includes('agent_uuid'));
|
||||
console.log('');
|
||||
|
||||
// ─── DELIVERABLE 5: 2 Docker Container Groups ──────────────────────────────
|
||||
console.log('📦 DELIVERABLE 5: 2 Docker Container Groups (Container 1: Proxy+MongoDB, Container 2: Backend+Frontend)');
|
||||
check('Container 1: Service mongodb', compose.includes('mongodb:'));
|
||||
check('Container 1: Service proxy', compose.includes('proxy:'));
|
||||
check('Container 2: Service backend', compose.includes('backend:'));
|
||||
check('Container 2: Service frontend', compose.includes('frontend:'));
|
||||
check('Network backone-infra (Container 1)', compose.includes('backone-infra'));
|
||||
check('Network backone-app (Container 2)', compose.includes('backone-app'));
|
||||
check('Proxy di backone-infra (isolated)', compose.includes('backone-infra'));
|
||||
check('Backend di backone-app (isolated)', compose.includes('backone-app'));
|
||||
check('MongoDB di kedua network (shared)', compose.includes('backone-infra') && compose.includes('backone-app'));
|
||||
check('Proxy depends on mongodb healthcheck', compose.includes('service_healthy'));
|
||||
check('PROXY_COLLECT_MODE di docker-compose', compose.includes('PROXY_COLLECT_MODE'));
|
||||
check('PROXY_AGENT_UUID di docker-compose', compose.includes('PROXY_AGENT_UUID'));
|
||||
check('PROXY_URL ke backend (untuk manual refresh)', compose.includes('PROXY_URL'));
|
||||
console.log('');
|
||||
|
||||
// ─── DELIVERABLE 6: Proxy API Endpoints ────────────────────────────────────
|
||||
console.log('📦 DELIVERABLE 6: Proxy REST API (port 4000)');
|
||||
check('GET /health', proxyIdx.includes("'/health'"));
|
||||
check('GET /status', proxyIdx.includes("'/status'"));
|
||||
check('GET /agents (list all agent UUIDs di MongoDB)', proxyIdx.includes("'/agents'"));
|
||||
check('POST /collect/all (trigger semua agent)', proxyIdx.includes("'/collect/all'"));
|
||||
check('POST /collect/:agentUuid (trigger spesifik)', proxyIdx.includes("'/collect/:agentUuid'"));
|
||||
console.log('');
|
||||
|
||||
// ─── DELIVERABLE 7: Proxy pisah dari backend ───────────────────────────────
|
||||
console.log('📦 DELIVERABLE 7: Proxy Terpisah dari Backend (sesuai pertanyaan user)');
|
||||
check('Proxy punya Dockerfile sendiri', fs.existsSync(path.join(ROOT, 'proxy/Dockerfile')));
|
||||
check('Proxy punya package.json sendiri', fs.existsSync(path.join(ROOT, 'proxy/package.json')));
|
||||
check('Proxy di folder terpisah (/proxy/)', fs.existsSync(path.join(ROOT, 'proxy/index.js')));
|
||||
check('Backend tidak mengimport dari proxy/', !server.includes("'../proxy'") && !dash.includes("'../proxy'"));
|
||||
check('Proxy tidak mengimport dari backend/', !r('proxy/index.js').includes("'../backend'"));
|
||||
check('Proxy hanya komunikasi ke MongoDB (tidak ke backend)', !r('proxy/collector.js').includes('3001'));
|
||||
check('Backend hanya POST ke proxy (bukan import)', dash.includes('axios.post') || server.includes('PROXY_URL'));
|
||||
console.log('');
|
||||
|
||||
// ─── DELIVERABLE 8: Environment Variable Dokumentasi ─────────────────────────────────
|
||||
console.log('📦 DELIVERABLE 8: Environment Variable Dokumentasi');
|
||||
check('PROXY_COLLECT_MODE terdokumentasi', envFileAll.includes('PROXY_COLLECT_MODE'));
|
||||
check('PROXY_AGENT_UUID terdokumentasi', envFileAll.includes('PROXY_AGENT_UUID'));
|
||||
check('Penjelasan Mode 1 (all)', envFileAll.toLowerCase().includes('mode 1') || envFileAll.includes('all'));
|
||||
check('Penjelasan Mode 2 (agent spesifik)', envFileAll.toLowerCase().includes('mode 2') || envFileAll.includes('agent'));
|
||||
check('MONGODB_URI ada', envFileAll.includes('MONGODB_URI'));
|
||||
check('PROXY_CRON_SCHEDULE ada', envFileAll.includes('PROXY_CRON') || envFileAll.includes('PROXY_COLLECT'));
|
||||
console.log('');
|
||||
|
||||
// ─── SUMMARY ───────────────────────────────────────────────────────────────
|
||||
console.log('══════════════════════════════════════════════════════');
|
||||
console.log(` FINAL: ${ok} PASSED | ${fail} FAILED`);
|
||||
if (fail === 0) {
|
||||
console.log(' STATUS: ✓ SEMUA DELIVERABLE TERPENUHI');
|
||||
} else {
|
||||
console.log(' STATUS: ✗ ADA YANG PERLU DIPERBAIKI — lihat item FAIL di atas');
|
||||
}
|
||||
console.log('══════════════════════════════════════════════════════\n');
|
||||
|
||||
if (fail > 0) process.exit(1);
|
||||
@@ -1,39 +0,0 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const excludeDirs = ['node_modules', '.next', 'scratch', 'test', '.git', 'dist'];
|
||||
|
||||
function getFiles(dir, fileList = []) {
|
||||
const files = fs.readdirSync(dir);
|
||||
for (const file of files) {
|
||||
const filePath = path.join(dir, file);
|
||||
const stat = fs.statSync(filePath);
|
||||
if (stat.isDirectory()) {
|
||||
if (!excludeDirs.includes(file)) {
|
||||
getFiles(filePath, fileList);
|
||||
}
|
||||
} else {
|
||||
if (['.ts', '.tsx', '.js', '.jsx'].includes(path.extname(file))) {
|
||||
fileList.push(filePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
return fileList;
|
||||
}
|
||||
|
||||
const allFiles = getFiles('C:\\Users\\demo\\Downloads\\Deep Package Inspection');
|
||||
|
||||
console.log('--- Checking file sizes (Rule 3: 256-LOC limit) ---');
|
||||
const longFiles = [];
|
||||
allFiles.forEach(file => {
|
||||
const content = fs.readFileSync(file, 'utf8');
|
||||
const lines = content.split('\n').length;
|
||||
if (lines > 256) {
|
||||
longFiles.push({ file, lines });
|
||||
}
|
||||
});
|
||||
|
||||
console.log(`Found ${longFiles.length} files exceeding 256 lines:`);
|
||||
longFiles.forEach(f => {
|
||||
console.log(`- ${path.relative('C:\\Users\\demo\\Downloads\\Deep Package Inspection', f.file)}: ${f.lines} lines`);
|
||||
});
|
||||
@@ -1,26 +0,0 @@
|
||||
const mongoose = require('mongoose');
|
||||
require('dotenv').config({ path: './.env.local' });
|
||||
|
||||
async function main() {
|
||||
const uri = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/backone_dpi';
|
||||
await mongoose.connect(uri);
|
||||
|
||||
const dbsList = await new mongoose.mongo.Admin(mongoose.connection.db).listDatabases();
|
||||
console.log('--- All Databases ---');
|
||||
for (const dbInfo of dbsList.databases) {
|
||||
const conn = mongoose.createConnection(`mongodb://127.0.0.1:27017/${dbInfo.name}`);
|
||||
await new Promise(resolve => conn.once('open', resolve));
|
||||
const collections = await conn.db.listCollections().toArray();
|
||||
for (const col of collections) {
|
||||
if (col.name === 'lookupapps') {
|
||||
const count = await conn.db.collection('lookupapps').countDocuments({});
|
||||
console.log(`DB: ${dbInfo.name} -> collection: lookupapps -> count: ${count}`);
|
||||
}
|
||||
}
|
||||
await conn.close();
|
||||
}
|
||||
|
||||
await mongoose.disconnect();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,33 +0,0 @@
|
||||
module.paths.unshift('c:\\Users\\demo\\Downloads\\Deep Package Inspection\\node_modules');
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = { host: '103.185.47.52', port: 2222, username: 'adminbackend', password: 'htEo7x6LsBQiEHHH', readyTimeout: 60000 };
|
||||
|
||||
async function main() {
|
||||
const conn = new Client();
|
||||
await new Promise((resolve, reject) => {
|
||||
conn.on('ready', resolve).on('error', reject).connect(SSH);
|
||||
});
|
||||
console.log('SSH connected.');
|
||||
|
||||
const runCmd = (cmd) => {
|
||||
return new Promise((resolve) => {
|
||||
conn.exec(cmd, (err, stream) => {
|
||||
if (err) { resolve(`Err: ${err.message}`); return; }
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => resolve(out.trim()));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const findConf = await runCmd('find /home/adminbackend -name "*nginx*.conf" -o -name "nginx.conf" 2>/dev/null');
|
||||
console.log('=== NGINX CONFS ===\n', findConf);
|
||||
|
||||
const nginxV = await runCmd('nginx -t 2>&1 || cat /etc/nginx/nginx.conf 2>/dev/null || echo "No nginx read access"');
|
||||
console.log('=== NGINX CONF OR STATUS ===\n', nginxV.substring(0, 1500));
|
||||
|
||||
conn.end();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,23 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
console.log('Searching for Nginx configurations under home directory...');
|
||||
conn.exec("find /home/adminbackend -name '*nginx*.conf' -o -name 'nginx.ssl.conf' 2>/dev/null", (err, stream) => {
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => {
|
||||
console.log('--- REMOTE NGINX CONFIGS ---');
|
||||
console.log(out);
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).connect(SSH);
|
||||
@@ -1,24 +0,0 @@
|
||||
const mongoose = require('mongoose');
|
||||
|
||||
async function main() {
|
||||
const LOCAL_URI = 'mongodb://127.0.0.1:27017/backone_dpi';
|
||||
await mongoose.connect(LOCAL_URI);
|
||||
const db = mongoose.connection.db;
|
||||
|
||||
console.log('--- Summaries with null/empty agent_uuid ---');
|
||||
const nullSummaries = await db.collection('summaries').find({
|
||||
$or: [
|
||||
{ agent_uuid: null },
|
||||
{ agent_uuid: '' },
|
||||
{ agent_uuid: { $exists: false } }
|
||||
]
|
||||
}).toArray();
|
||||
|
||||
console.log(`Found ${nullSummaries.length} documents:`);
|
||||
nullSummaries.forEach(s => {
|
||||
console.log(`_id: ${s._id}, timestamp: ${s.timestamp}, site_uuid: ${s.site_uuid}, agent_label: ${s.agent_label}`);
|
||||
});
|
||||
|
||||
await mongoose.disconnect();
|
||||
}
|
||||
main();
|
||||
@@ -1,22 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
conn.exec("find /home/adminbackend/web/demoplace.my.id/public_html -name '*\\\\*'", (err, stream) => {
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => {
|
||||
console.log('--- REMOTE FILES WITH BACKSLASHES ---');
|
||||
console.log(out);
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).connect(SSH);
|
||||
@@ -1,22 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
conn.exec("find /home/adminbackend/conf -type f 2>/dev/null", (err, stream) => {
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => {
|
||||
console.log('--- REMOTE CONF FILES ---');
|
||||
console.log(out);
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).connect(SSH);
|
||||
@@ -1,27 +0,0 @@
|
||||
// test/find_mongoose_chunk.js
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const filePath = path.join(__dirname, '../.next/server/chunks/ssr/[root-of-the-server]__081-pwf._.js');
|
||||
|
||||
try {
|
||||
const content = fs.readFileSync(filePath, 'utf8');
|
||||
const lines = content.split('\n');
|
||||
console.log(`Total lines: ${lines.length}`);
|
||||
|
||||
let matchCount = 0;
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
if (lines[i].includes('mongoose-8b99e611e7552af3')) {
|
||||
console.log(`Line ${i + 1}:`);
|
||||
// Print a slice of the line around the match
|
||||
const index = lines[i].indexOf('mongoose-8b99e611e7552af3');
|
||||
const start = Math.max(0, index - 100);
|
||||
const end = Math.min(lines[i].length, index + 100);
|
||||
console.log(lines[i].slice(start, end));
|
||||
matchCount++;
|
||||
if (matchCount > 5) break;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Error reading file:", err.message);
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
module.paths.unshift('c:\\Users\\demo\\Downloads\\Deep Package Inspection\\node_modules');
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = { host: '103.185.47.52', port: 2222, username: 'adminbackend', password: 'htEo7x6LsBQiEHHH', readyTimeout: 60000 };
|
||||
|
||||
async function main() {
|
||||
const conn = new Client();
|
||||
await new Promise((resolve, reject) => {
|
||||
conn.on('ready', resolve).on('error', reject).connect(SSH);
|
||||
});
|
||||
console.log('SSH connected.');
|
||||
|
||||
const runCmd = (cmd) => {
|
||||
return new Promise((resolve) => {
|
||||
conn.exec(cmd, (err, stream) => {
|
||||
if (err) { resolve(`Err: ${err.message}`); return; }
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => resolve(out.trim()));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// Copy fonts directory to public_html root
|
||||
const copyRes = await runCmd('cp -r /home/adminbackend/web/demoplace.my.id/public_html/public/fonts /home/adminbackend/web/demoplace.my.id/public_html/ && echo "Copy successful" || echo "Copy failed"');
|
||||
console.log('=== COPY FONTS ===\n', copyRes);
|
||||
|
||||
const checkFile = await runCmd('ls -la /home/adminbackend/web/demoplace.my.id/public_html/fonts/BackOneLogo-Regular.ttf');
|
||||
console.log('=== CHECK FILE ===\n', checkFile);
|
||||
|
||||
conn.end();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,43 +0,0 @@
|
||||
// test/fix_blacklist_indexes.js
|
||||
const mongoose = require('mongoose');
|
||||
|
||||
async function run() {
|
||||
console.log("Connecting to MongoDB...");
|
||||
await mongoose.connect('mongodb://127.0.0.1:27017/backone_dpi');
|
||||
console.log("Connected successfully!");
|
||||
|
||||
const db = mongoose.connection.db;
|
||||
const collection = db.collection('blacklistrules');
|
||||
|
||||
console.log("Dropping all existing indexes on blacklistrules collection...");
|
||||
try {
|
||||
await collection.dropIndexes();
|
||||
console.log("✓ Indexes dropped successfully.");
|
||||
} catch (err) {
|
||||
console.warn("Could not drop indexes (probably collection doesn't exist yet):", err.message);
|
||||
}
|
||||
|
||||
console.log("Cleaning up old blacklist rules that don't have agent_uuid...");
|
||||
const deleteResult = await collection.deleteMany({
|
||||
$or: [
|
||||
{ agent_uuid: { $exists: false } },
|
||||
{ agent_uuid: null },
|
||||
{ agent_uuid: "" }
|
||||
]
|
||||
});
|
||||
console.log(`✓ Deleted ${deleteResult.deletedCount} legacy blacklist rules.`);
|
||||
|
||||
console.log("Rebuilding Mongoose model indexes...");
|
||||
const { BlacklistRule } = require('../backend/models/Schemas');
|
||||
await BlacklistRule.cleanIndexes();
|
||||
await BlacklistRule.createIndexes();
|
||||
console.log("✓ New compound indexes built successfully!");
|
||||
|
||||
await mongoose.disconnect();
|
||||
console.log("Disconnected from MongoDB.");
|
||||
}
|
||||
|
||||
run().catch(err => {
|
||||
console.error("Migration failed:", err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,33 +0,0 @@
|
||||
module.paths.unshift('c:\\Users\\demo\\Downloads\\Deep Package Inspection\\node_modules');
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = { host: '103.185.47.52', port: 2222, username: 'adminbackend', password: 'htEo7x6LsBQiEHHH', readyTimeout: 60000 };
|
||||
|
||||
async function main() {
|
||||
const conn = new Client();
|
||||
await new Promise((resolve, reject) => {
|
||||
conn.on('ready', resolve).on('error', reject).connect(SSH);
|
||||
});
|
||||
console.log('SSH connected.');
|
||||
|
||||
const runCmd = (cmd) => {
|
||||
return new Promise((resolve) => {
|
||||
conn.exec(cmd, (err, stream) => {
|
||||
if (err) { resolve(`Err: ${err.message}`); return; }
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => resolve(out.trim()));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const restartRes = await runCmd('/home/adminbackend/.npm-global/bin/pm2 restart all');
|
||||
console.log('=== PM2 RESTART ALL ===\n', restartRes);
|
||||
|
||||
const pm2List = await runCmd('/home/adminbackend/.npm-global/bin/pm2 list');
|
||||
console.log('=== PM2 LIST ===\n', pm2List);
|
||||
|
||||
conn.end();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,22 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
const path = require('path');
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
conn.exec("node -e \"const fs = require('fs'); const path = require('path'); const root = '/home/adminbackend/web/demoplace.my.id/public_html'; function getFiles(dir, files = {}) { try { const list = fs.readdirSync(dir); for (const item of list) { const fullPath = path.join(dir, item); const stat = fs.statSync(fullPath); if (stat.isDirectory()) { if (item !== 'node_modules' && item !== '.next' && item !== '.git') getFiles(fullPath, files); } else { files[path.relative(root, fullPath)] = true; } } } catch(e) {} return files; } console.log(JSON.stringify(Object.keys(getFiles(path.join(root, 'src')))));\"", (err, stream) => {
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => {
|
||||
console.log('Remote keys:', out);
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).connect(SSH);
|
||||
@@ -1,63 +0,0 @@
|
||||
// test/get_db_date_range.js
|
||||
const mongoose = require('mongoose');
|
||||
|
||||
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/backone_dpi';
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
await mongoose.connect(MONGODB_URI);
|
||||
console.log('✓ Connected to Production MongoDB');
|
||||
|
||||
const db = mongoose.connection.db;
|
||||
const summariesCol = db.collection('summaries');
|
||||
|
||||
// Get list of agents
|
||||
const agents = await summariesCol.distinct('agent_uuid', { agent_uuid: { $ne: null } });
|
||||
console.log('Agents found in database:', agents);
|
||||
|
||||
console.log('\n--- DATE RANGE ANALYSIS PER AGENT ---');
|
||||
for (const agentUuid of agents) {
|
||||
// Find earliest and latest timestamp in summaries for this agent
|
||||
const bounds = await summariesCol.aggregate([
|
||||
{ $match: { agent_uuid: agentUuid } },
|
||||
{
|
||||
$group: {
|
||||
_id: '$agent_uuid',
|
||||
minDate: { $min: '$timestamp' },
|
||||
maxDate: { $max: '$timestamp' },
|
||||
count: { $sum: 1 }
|
||||
}
|
||||
}
|
||||
]).toArray();
|
||||
|
||||
if (bounds.length > 0) {
|
||||
const { minDate, maxDate, count } = bounds[0];
|
||||
console.log(`Agent: ${agentUuid}`);
|
||||
console.log(` Earliest Date: ${minDate ? new Date(minDate).toLocaleString('id-ID', { timeZone: 'Asia/Jakarta' }) : 'N/A'}`);
|
||||
console.log(` Latest Date : ${maxDate ? new Date(maxDate).toLocaleString('id-ID', { timeZone: 'Asia/Jakarta' }) : 'N/A'}`);
|
||||
console.log(` Total Summaries Documents: ${count}`);
|
||||
} else {
|
||||
console.log(`Agent: ${agentUuid} (No summary documents found)`);
|
||||
}
|
||||
}
|
||||
|
||||
// Also get overall collections bounds
|
||||
console.log('\n--- OVERALL COLLECTION BOUNDS ---');
|
||||
const colsToCheck = ['flows', 'appstats', 'threats', 'events'];
|
||||
for (const colName of colsToCheck) {
|
||||
const col = db.collection(colName);
|
||||
const firstDoc = await col.find().sort({ timestamp: 1 }).limit(1).toArray();
|
||||
const lastDoc = await col.find().sort({ timestamp: -1 }).limit(1).toArray();
|
||||
|
||||
console.log(`Collection: ${colName}`);
|
||||
console.log(` Earliest Doc: ${firstDoc[0]?.timestamp ? new Date(firstDoc[0].timestamp).toLocaleString('id-ID', { timeZone: 'Asia/Jakarta' }) : 'N/A'}`);
|
||||
console.log(` Latest Doc : ${lastDoc[0]?.timestamp ? new Date(lastDoc[0].timestamp).toLocaleString('id-ID', { timeZone: 'Asia/Jakarta' }) : 'N/A'}`);
|
||||
}
|
||||
|
||||
await mongoose.disconnect();
|
||||
} catch (err) {
|
||||
console.error('Error:', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -1,34 +0,0 @@
|
||||
module.paths.unshift('c:\\Users\\demo\\Downloads\\Deep Package Inspection\\node_modules');
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = { host: '103.185.47.52', port: 2222, username: 'adminbackend', password: 'htEo7x6LsBQiEHHH', readyTimeout: 60000 };
|
||||
|
||||
async function main() {
|
||||
const conn = new Client();
|
||||
await new Promise((resolve, reject) => {
|
||||
conn.on('ready', resolve).on('error', reject).connect(SSH);
|
||||
});
|
||||
console.log('SSH connected.');
|
||||
|
||||
const runCmd = (cmd) => {
|
||||
return new Promise((resolve) => {
|
||||
conn.exec(cmd, (err, stream) => {
|
||||
if (err) { resolve(`Err: ${err.message}`); return; }
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.stderr.on('data', d => out += `[stderr] ${d}`);
|
||||
stream.on('close', () => resolve(out.trim()));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const gitLog = await runCmd('cd /home/adminbackend/web/demoplace.my.id/public_html && git log -n 5 --oneline');
|
||||
console.log('=== GIT LOG REMOTE ===\n', gitLog);
|
||||
|
||||
const gitStatus = await runCmd('cd /home/adminbackend/web/demoplace.my.id/public_html && git status');
|
||||
console.log('=== GIT STATUS REMOTE ===\n', gitStatus);
|
||||
|
||||
conn.end();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,20 +0,0 @@
|
||||
const mongoose = require('mongoose');
|
||||
|
||||
const MONGODB_URI = process.env.MONGODB_URI || "mongodb://127.0.0.1:27017/backone_dpi";
|
||||
|
||||
async function run() {
|
||||
console.log('Connecting to Production MongoDB...');
|
||||
await mongoose.connect(MONGODB_URI);
|
||||
console.log('Connected.');
|
||||
|
||||
const db = mongoose.connection.db;
|
||||
const agents = await db.collection('agent_registry').find({}).toArray();
|
||||
console.log('Total agents in agent_registry:', agents.length);
|
||||
for (const agent of agents) {
|
||||
console.log(`Agent UUID: ${agent.uuid}, Label: ${agent.label}, Site UUID: ${agent.site_uuid}, Organization: ${agent.organization_uuid}`);
|
||||
}
|
||||
|
||||
await mongoose.disconnect();
|
||||
}
|
||||
|
||||
run().catch(console.error);
|
||||
@@ -1,54 +0,0 @@
|
||||
// test/inspect-production-mongodb.js
|
||||
const mongoose = require('c:/Users/demo/Downloads/Deep Package Inspection/backend/node_modules/mongoose');
|
||||
|
||||
const MONGODB_URI = process.env.MONGODB_URI || "mongodb://127.0.0.1:27017/backone_dpi";
|
||||
|
||||
async function run() {
|
||||
console.log('Connecting to Production MongoDB...');
|
||||
await mongoose.connect(MONGODB_URI);
|
||||
console.log('Connected.');
|
||||
|
||||
const db = mongoose.connection.db;
|
||||
const count = await db.collection('summaries').countDocuments({});
|
||||
console.log('Total summaries documents in DB:', count);
|
||||
|
||||
// Find latest documents
|
||||
console.log('--- LATEST 5 DOCUMENTS ---');
|
||||
const latest = await db.collection('summaries').find({}).sort({ timestamp: -1 }).limit(5).toArray();
|
||||
for (const doc of latest) {
|
||||
console.log(`ID: ${doc._id}, Time: ${doc.timestamp}, Agent: ${doc.agent_uuid}, Site: ${doc.site_uuid}, Down: ${doc.bandwidth_down}, Up: ${doc.bandwidth_up}, Flows: ${doc.active_flows}`);
|
||||
}
|
||||
|
||||
// Find site-level summaries in last 24 hours
|
||||
const twentyFourHoursAgo = new Date(Date.now() - 24 * 3600000);
|
||||
const siteSummaries = await db.collection('summaries').find({
|
||||
agent_uuid: null,
|
||||
timestamp: { $gte: twentyFourHoursAgo }
|
||||
}).toArray();
|
||||
console.log('--- SITE-LEVEL SUMMARIES IN LAST 24 HOURS ---');
|
||||
console.log('Count:', siteSummaries.length);
|
||||
|
||||
const massiveDocs = siteSummaries.filter(d => (d.bandwidth_down || 0) > 1e9);
|
||||
console.log('Number of documents with Down > 1 GB:', massiveDocs.length);
|
||||
for (const doc of massiveDocs.slice(0, 10)) {
|
||||
console.log(`ID: ${doc._id}, Time: ${doc.timestamp}, Down: ${doc.bandwidth_down}`);
|
||||
}
|
||||
|
||||
if (siteSummaries.length > 0) {
|
||||
let sumDown = 0;
|
||||
let sumUp = 0;
|
||||
for (const doc of siteSummaries) {
|
||||
sumDown += (doc.bandwidth_down || 0);
|
||||
sumUp += (doc.bandwidth_up || 0);
|
||||
}
|
||||
console.log(`Total Download (Sum): ${sumDown} bytes (${(sumDown / 1e12).toFixed(2)} TB)`);
|
||||
console.log(`Total Upload (Sum): ${sumUp} bytes (${(sumUp / 1e12).toFixed(2)} TB)`);
|
||||
console.log(`Average Flows: ${siteSummaries[0].active_flows}`);
|
||||
console.log('Sample Document from last 24 hours:');
|
||||
console.log(JSON.stringify(siteSummaries[0], null, 2));
|
||||
}
|
||||
|
||||
await mongoose.disconnect();
|
||||
}
|
||||
|
||||
run().catch(console.error);
|
||||
@@ -1,34 +0,0 @@
|
||||
const rootMongoose = require('mongoose');
|
||||
const proxyMongoose = require('../proxy/node_modules/mongoose');
|
||||
const { LookupApp } = require('../proxy/models/Schemas');
|
||||
|
||||
async function main() {
|
||||
const uri = 'mongodb://127.0.0.1:27017/backone_dpi';
|
||||
console.log('Connecting Root Mongoose...');
|
||||
await rootMongoose.connect(uri);
|
||||
console.log('Root Mongoose connection state:', rootMongoose.connection.readyState);
|
||||
console.log('Proxy Mongoose connection state BEFORE:', proxyMongoose.connection.readyState);
|
||||
|
||||
try {
|
||||
const count = await LookupApp.countDocuments({});
|
||||
console.log('Count from LookupApp:', count);
|
||||
} catch (err) {
|
||||
console.log('Error counting from LookupApp:', err.message);
|
||||
}
|
||||
|
||||
console.log('Connecting Proxy Mongoose...');
|
||||
await proxyMongoose.connect(uri);
|
||||
console.log('Proxy Mongoose connection state AFTER:', proxyMongoose.connection.readyState);
|
||||
|
||||
try {
|
||||
const count = await LookupApp.countDocuments({});
|
||||
console.log('Count from LookupApp after proxy connect:', count);
|
||||
} catch (err) {
|
||||
console.log('Error counting from LookupApp after proxy connect:', err.message);
|
||||
}
|
||||
|
||||
await rootMongoose.disconnect();
|
||||
await proxyMongoose.disconnect();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,31 +0,0 @@
|
||||
const mongoose = require('mongoose');
|
||||
const dotenv = require('dotenv');
|
||||
const path = require('path');
|
||||
|
||||
// Load environment variables
|
||||
dotenv.config({ path: path.join(__dirname, '../.env.production') });
|
||||
|
||||
const { Threat, Event } = require('../backend/models/Schemas');
|
||||
|
||||
async function main() {
|
||||
console.log('Connecting to database...');
|
||||
await mongoose.connect(process.env.MONGODB_URI);
|
||||
console.log('Connected!');
|
||||
|
||||
console.log('\n--- RAW THREAT DOCS ---');
|
||||
const threats = await Threat.find().lean();
|
||||
console.log(JSON.stringify(threats, null, 2));
|
||||
|
||||
console.log('\n--- RAW EVENTS (Cybersecurity / High severity) ---');
|
||||
const events = await Event.find({
|
||||
$or: [
|
||||
{ severity: { $in: ['Critical', 'High'] } },
|
||||
{ category_label: 'Cybersecurity' }
|
||||
]
|
||||
}).lean();
|
||||
console.log(JSON.stringify(events, null, 2));
|
||||
|
||||
await mongoose.disconnect();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,27 +0,0 @@
|
||||
// test/inspect_pm2_config.js
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const sshConfig = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH'
|
||||
};
|
||||
|
||||
async function main() {
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
conn.exec('find /home/adminbackend/backone-production -name "server.js"', (err, stream) => {
|
||||
if (err) throw err;
|
||||
let out = '';
|
||||
stream.on('close', () => {
|
||||
conn.end();
|
||||
console.log("Found server.js at:\n", out);
|
||||
}).on('data', (data) => {
|
||||
out += data;
|
||||
});
|
||||
});
|
||||
}).connect(sshConfig);
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -1,50 +0,0 @@
|
||||
// test/inspect_remote_structure.js
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const sshConfig = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH'
|
||||
};
|
||||
|
||||
async function runSSHCommands(commands) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
let combinedCmd = commands.join(' && echo "=== CMD_SEPARATOR ===" && ');
|
||||
conn.exec(combinedCmd, (err, stream) => {
|
||||
if (err) {
|
||||
conn.end();
|
||||
return reject(err);
|
||||
}
|
||||
let out = '';
|
||||
stream.on('close', (code, signal) => {
|
||||
conn.end();
|
||||
resolve(out);
|
||||
}).on('data', (data) => {
|
||||
out += data;
|
||||
}).stderr.on('data', (data) => {
|
||||
out += data;
|
||||
});
|
||||
});
|
||||
}).on('error', reject).connect(sshConfig);
|
||||
});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const commands = [
|
||||
'echo "=== LS -LA ROOT ===" && ls -la /home/adminbackend/backone-production/',
|
||||
'echo "=== LS -LA .NEXT ===" && ls -la /home/adminbackend/backone-production/.next/ || echo "no .next"',
|
||||
'echo "=== LS -LA STANDALONE ===" && ls -la /home/adminbackend/backone-production/.next/standalone/ || echo "no standalone"'
|
||||
];
|
||||
|
||||
try {
|
||||
const output = await runSSHCommands(commands);
|
||||
console.log(output);
|
||||
} catch (err) {
|
||||
console.error("SSH Commands failed:", err.message);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -1,64 +0,0 @@
|
||||
const fs = require('fs');
|
||||
const mongoose = require('mongoose');
|
||||
|
||||
async function main() {
|
||||
const dumpPath = 'C:\\Users\\demo\\.gemini\\antigravity-ide\\scratch\\remote_db_dump.json';
|
||||
if (!fs.existsSync(dumpPath)) {
|
||||
console.error('Error: Dump file not found.');
|
||||
return;
|
||||
}
|
||||
|
||||
const rawData = fs.readFileSync(dumpPath, 'utf8');
|
||||
const data = JSON.parse(rawData);
|
||||
|
||||
const LOCAL_URI = 'mongodb://127.0.0.1:27017/backone_dpi';
|
||||
console.log('Connecting to local MongoDB...');
|
||||
await mongoose.connect(LOCAL_URI);
|
||||
console.log('✓ Connected to local MongoDB.');
|
||||
|
||||
const db = mongoose.connection.db;
|
||||
|
||||
for (const [colName, info] of Object.entries(data)) {
|
||||
if (info.docs) {
|
||||
console.log(`\n--- Loading collection "${colName}" (${info.docs.length} docs) ---`);
|
||||
|
||||
// Clear local collection first
|
||||
await db.collection(colName).deleteMany({});
|
||||
console.log(`- Cleared local "${colName}"`);
|
||||
|
||||
// If we have documents to insert, convert any _id strings to ObjectIds (if appropriate) and insert
|
||||
if (info.docs.length > 0) {
|
||||
const cleanedDocs = info.docs.map(doc => {
|
||||
// MongoDB serialization via JSON converts ObjectId to string/object representation.
|
||||
// Let's restore _id to ObjectId.
|
||||
if (doc._id) {
|
||||
try {
|
||||
if (typeof doc._id === 'string') {
|
||||
doc._id = new mongoose.Types.ObjectId(doc._id);
|
||||
} else if (doc._id.$oid) {
|
||||
doc._id = new mongoose.Types.ObjectId(doc._id.$oid);
|
||||
}
|
||||
} catch (e) {
|
||||
// fallback to original if not a valid ObjectId format
|
||||
}
|
||||
}
|
||||
// Also restore date fields
|
||||
for (const key of Object.keys(doc)) {
|
||||
if (typeof doc[key] === 'string' && doc[key].match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/)) {
|
||||
doc[key] = new Date(doc[key]);
|
||||
}
|
||||
}
|
||||
return doc;
|
||||
});
|
||||
|
||||
await db.collection(colName).insertMany(cleanedDocs);
|
||||
console.log(`- Inserted ${cleanedDocs.length} documents into "${colName}"`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await mongoose.disconnect();
|
||||
console.log('\n✓ Successfully loaded remote dump into local database!');
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,35 +0,0 @@
|
||||
const mongoose = require('mongoose');
|
||||
const path = require('path');
|
||||
|
||||
require('dotenv').config({ path: path.join(__dirname, '../.env.local') });
|
||||
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/backone_dpi';
|
||||
|
||||
async function run() {
|
||||
console.log('Connecting to:', MONGODB_URI);
|
||||
try {
|
||||
await mongoose.connect(MONGODB_URI, {
|
||||
serverSelectionTimeoutMS: 5000,
|
||||
});
|
||||
console.log('Connected!');
|
||||
|
||||
const db = mongoose.connection.db;
|
||||
const collections = await db.listCollections().toArray();
|
||||
console.log('Collections:', collections.map(c => c.name));
|
||||
|
||||
// Try raw query on users collection
|
||||
const users = await db.collection('users').find({}).toArray();
|
||||
console.log('Raw users in DB:', users.map(u => ({
|
||||
username: u.username,
|
||||
role: u.role,
|
||||
site_uuid: u.site_uuid,
|
||||
agent_uuid: u.agent_uuid,
|
||||
created_by: u.created_by
|
||||
})));
|
||||
|
||||
await mongoose.disconnect();
|
||||
} catch (err) {
|
||||
console.error('Error:', err);
|
||||
}
|
||||
}
|
||||
|
||||
run();
|
||||
@@ -1,60 +0,0 @@
|
||||
// test/performance_and_modal_blur_test.js
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// TDD Test Suite: Modal Backdrop Blur & High Performance Query Optimization
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
console.log('🧪 Running TDD Test: Modal Backdrop Blur & Performance Optimization');
|
||||
|
||||
// 1. Verify DeviceDetailModal backdrop overlay has backdrop-filter styling
|
||||
const modalPath = path.resolve(__dirname, '../src/components/ui/DeviceDetailModal.tsx');
|
||||
const modalContent = fs.readFileSync(modalPath, 'utf8');
|
||||
|
||||
assert(
|
||||
modalContent.includes('backdropFilter') || modalContent.includes('backdrop-blur'),
|
||||
'FAIL: DeviceDetailModal must have backdrop-blur filter on modal overlay'
|
||||
);
|
||||
assert(
|
||||
modalContent.includes('fixed inset-0') && modalContent.includes('bg-slate-950') || modalContent.includes('bg-black'),
|
||||
'FAIL: DeviceDetailModal must use fixed inset-0 overlay for modal backdrop blur'
|
||||
);
|
||||
|
||||
// 2. Verify MongoDB Schemas define compound indexes on Flow for src_ip and dst_ip
|
||||
const schemasPath = path.resolve(__dirname, '../backend/models/Schemas.js');
|
||||
const schemasContent = fs.readFileSync(schemasPath, 'utf8');
|
||||
|
||||
assert(
|
||||
schemasContent.includes('FlowSchema.index({ agent_uuid: 1, src_ip: 1'),
|
||||
'FAIL: Schemas.js MUST define compound index FlowSchema.index({ agent_uuid: 1, src_ip: 1, timestamp: -1 })'
|
||||
);
|
||||
assert(
|
||||
schemasContent.includes('FlowSchema.index({ agent_uuid: 1, dst_ip: 1'),
|
||||
'FAIL: Schemas.js MUST define compound index FlowSchema.index({ agent_uuid: 1, dst_ip: 1, timestamp: -1 })'
|
||||
);
|
||||
|
||||
// 3. Verify deviceDetailsHandler uses indexed query optimization
|
||||
const handlerPath = path.resolve(__dirname, '../backend/routes/deviceDetailsHandler.js');
|
||||
const handlerContent = fs.readFileSync(handlerPath, 'utf8');
|
||||
|
||||
assert(
|
||||
!handlerContent.includes('limit(5000)'),
|
||||
'FAIL: deviceDetailsHandler must NOT load 5000 un-indexed flows on single device click'
|
||||
);
|
||||
assert(
|
||||
handlerContent.includes('Promise.all') || handlerContent.includes('src_ip'),
|
||||
'FAIL: deviceDetailsHandler MUST execute optimized parallel queries for device details'
|
||||
);
|
||||
|
||||
// 4. Verify getAgents server action uses parallelized Promise.all for agent status checks
|
||||
const agentsActionPath = path.resolve(__dirname, '../src/lib/actions/agents.ts');
|
||||
const agentsActionContent = fs.readFileSync(agentsActionPath, 'utf8');
|
||||
|
||||
assert(
|
||||
agentsActionContent.includes('Promise.all') && agentsActionContent.includes('agentSource.map'),
|
||||
'FAIL: getAgents in agents.ts MUST use Promise.all to query agent statuses in parallel'
|
||||
);
|
||||
|
||||
console.log('✅ ALL TDD TESTS FOR PERFORMANCE & MODAL BLUR PASSED!');
|
||||
@@ -1,30 +0,0 @@
|
||||
module.paths.unshift('c:\\Users\\demo\\Downloads\\Deep Package Inspection\\node_modules');
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = { host: '103.185.47.52', port: 2222, username: 'adminbackend', password: 'htEo7x6LsBQiEHHH', readyTimeout: 60000 };
|
||||
|
||||
async function main() {
|
||||
const conn = new Client();
|
||||
await new Promise((resolve, reject) => {
|
||||
conn.on('ready', resolve).on('error', reject).connect(SSH);
|
||||
});
|
||||
console.log('SSH connected.');
|
||||
|
||||
const runCmd = (cmd) => {
|
||||
return new Promise((resolve) => {
|
||||
conn.exec(cmd, (err, stream) => {
|
||||
if (err) { resolve(`Err: ${err.message}`); return; }
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => resolve(out.trim()));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const showFront = await runCmd('pm2 show demoplace-frontend || npx pm2 show demoplace-frontend');
|
||||
console.log('=== PM2 SHOW FRONTEND ===\n', showFront);
|
||||
|
||||
conn.end();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,14 +0,0 @@
|
||||
const mongoose = require('mongoose');
|
||||
|
||||
async function main() {
|
||||
const LOCAL_URI = 'mongodb://127.0.0.1:27017/backone_dpi';
|
||||
await mongoose.connect(LOCAL_URI);
|
||||
const db = mongoose.connection.db;
|
||||
|
||||
const distinctUuids = await db.collection('summaries').distinct('agent_uuid');
|
||||
console.log('Distinct agent_uuid values in summaries:');
|
||||
console.log(distinctUuids.map(u => typeof u === 'string' ? `"${u}"` : u));
|
||||
|
||||
await mongoose.disconnect();
|
||||
}
|
||||
main();
|
||||
@@ -1,21 +0,0 @@
|
||||
const mongoose = require('mongoose');
|
||||
|
||||
async function main() {
|
||||
const LOCAL_URI = 'mongodb://127.0.0.1:27017/backone_dpi';
|
||||
await mongoose.connect(LOCAL_URI);
|
||||
const db = mongoose.connection.db;
|
||||
|
||||
const doc = await db.collection('summaries').findOne({
|
||||
$or: [
|
||||
{ agent_uuid: null },
|
||||
{ agent_uuid: '' },
|
||||
{ agent_uuid: { $exists: false } }
|
||||
]
|
||||
});
|
||||
|
||||
console.log('Document with null/empty agent_uuid:');
|
||||
console.log(JSON.stringify(doc, null, 2));
|
||||
|
||||
await mongoose.disconnect();
|
||||
}
|
||||
main();
|
||||
@@ -1,30 +0,0 @@
|
||||
const jwt = require('jsonwebtoken');
|
||||
const axios = require('axios');
|
||||
require('dotenv').config({ path: './.env.local' });
|
||||
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'super-secret-backone-key';
|
||||
|
||||
async function main() {
|
||||
console.log('Generating auth token...');
|
||||
// Create a mock authenticated user token
|
||||
const payload = {
|
||||
id: 'mock-admin-id',
|
||||
role: 'SUPER_ADMIN',
|
||||
email: 'admin@backone.local',
|
||||
site_uuid: 'mock-site-uuid'
|
||||
};
|
||||
const token = jwt.sign(payload, JWT_SECRET, { expiresIn: '1h' });
|
||||
|
||||
console.log('Querying local backend `/api/dashboard/lookup/applications` with token...');
|
||||
const res = await axios.get('http://127.0.0.1:3001/api/dashboard/lookup/applications', {
|
||||
params: { limit: 5 },
|
||||
headers: {
|
||||
Cookie: `token=${token}`
|
||||
}
|
||||
});
|
||||
|
||||
console.log('Response Status:', res.status);
|
||||
console.log('Response Data:', JSON.stringify(res.data, null, 2));
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,23 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
console.log('Reading PM2 default log files...');
|
||||
conn.exec("ls -l ~/.pm2/logs/; tail -n 50 ~/.pm2/logs/backone-frontend-out.log; tail -n 50 ~/.pm2/logs/backone-frontend-error.log", (err, stream) => {
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => {
|
||||
console.log('--- DEFAULT PM2 LOG FILES ---');
|
||||
console.log(out);
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).connect(SSH);
|
||||
@@ -1,22 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
conn.exec("cat /home/adminbackend/conf/web/demoplace.my.id/apache2.ssl.conf", (err, stream) => {
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => {
|
||||
console.log('--- REMOTE APACHE SSL CONF CONTENT ---');
|
||||
console.log(out);
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).connect(SSH);
|
||||
@@ -1,22 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
conn.exec("tail -n 50 /home/adminbackend/web/demoplace.my.id/public_html/logs/backend-out.log; tail -n 50 /home/adminbackend/web/demoplace.my.id/public_html/logs/backend-error.log", (err, stream) => {
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => {
|
||||
console.log('--- REMOTE BACKEND LOG FILES ---');
|
||||
console.log(out);
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).connect(SSH);
|
||||
@@ -1,22 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
conn.exec("ls -l /home/adminbackend/conf/web/demoplace.my.id/nginx.ssl.conf_* /home/adminbackend/conf/web/demoplace.my.id/apache2.ssl.conf_* 2>/dev/null; cat /home/adminbackend/conf/web/demoplace.my.id/nginx.ssl.conf_* 2>/dev/null", (err, stream) => {
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => {
|
||||
console.log('--- REMOTE NGINX CUSTOM CONFIG ---');
|
||||
console.log(out);
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).connect(SSH);
|
||||
@@ -1,22 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
conn.exec("tail -n 50 /home/adminbackend/web/demoplace.my.id/public_html/logs/frontend-out.log; tail -n 50 /home/adminbackend/web/demoplace.my.id/public_html/logs/frontend-error.log", (err, stream) => {
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => {
|
||||
console.log('--- REMOTE FRONTEND LOG FILES ---');
|
||||
console.log(out);
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).connect(SSH);
|
||||
@@ -1,22 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
conn.exec("cat /home/adminbackend/web/demoplace.my.id/public_html/.htaccess", (err, stream) => {
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => {
|
||||
console.log('--- REMOTE HTACCESS ---');
|
||||
console.log(out);
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).connect(SSH);
|
||||
@@ -1,23 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
console.log('Fetching latest backend logs from PM2 default dir...');
|
||||
conn.exec("tail -n 100 ~/.pm2/logs/backone-backend-out.log; tail -n 100 ~/.pm2/logs/backone-backend-error.log", (err, stream) => {
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => {
|
||||
console.log('--- LATEST BACKEND LOGS ---');
|
||||
console.log(out);
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).connect(SSH);
|
||||
@@ -1,23 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
console.log('Fetching latest frontend error logs from PM2...');
|
||||
conn.exec("tail -n 150 ~/.pm2/logs/backone-frontend-error.log", (err, stream) => {
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => {
|
||||
console.log('--- LATEST FRONTEND ERRORS ---');
|
||||
console.log(out);
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).connect(SSH);
|
||||
@@ -1,22 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
conn.exec("cat /home/adminbackend/conf/web/demoplace.my.id/nginx.ssl.conf", (err, stream) => {
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => {
|
||||
console.log('--- REMOTE NGINX SSL CONF CONTENT ---');
|
||||
console.log(out);
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).connect(SSH);
|
||||
@@ -1,34 +0,0 @@
|
||||
module.paths.unshift('c:\\Users\\demo\\Downloads\\Deep Package Inspection\\node_modules');
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = { host: '103.185.47.52', port: 2222, username: 'adminbackend', password: 'htEo7x6LsBQiEHHH', readyTimeout: 60000 };
|
||||
|
||||
async function main() {
|
||||
const conn = new Client();
|
||||
await new Promise((resolve, reject) => {
|
||||
conn.on('ready', resolve).on('error', reject).connect(SSH);
|
||||
});
|
||||
console.log('SSH connected.');
|
||||
|
||||
const runCmd = (cmd) => {
|
||||
return new Promise((resolve) => {
|
||||
conn.exec(cmd, (err, stream) => {
|
||||
if (err) { resolve(`Err: ${err.message}`); return; }
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => resolve(out.trim()));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// Find Nginx confs for demoplace.my.id
|
||||
const findConf = await runCmd('find /etc/nginx/ -name "*demoplace*" 2>/dev/null || echo "No find access"');
|
||||
console.log('=== FIND DEMOPLACE NGINX ===\n', findConf);
|
||||
|
||||
const confContent = await runCmd('cat /etc/nginx/conf.d/domains/demoplace.my.id.conf || cat /etc/nginx/sites-enabled/demoplace.my.id || echo "No read access"');
|
||||
console.log('=== DEMOPLACE CONF CONTENT ===\n', confContent);
|
||||
|
||||
conn.end();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,22 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
conn.exec("/home/adminbackend/.npm-global/bin/pm2 logs backone-frontend --lines 50 --raw --nobuster", (err, stream) => {
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => {
|
||||
console.log('--- PM2 FRONTEND LOGS ---');
|
||||
console.log(out);
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).connect(SSH);
|
||||
@@ -1,22 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
conn.exec("cat /home/adminbackend/web/demoplace.my.id/public_html/proxy.php", (err, stream) => {
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => {
|
||||
console.log('--- REMOTE PROXY PHP ---');
|
||||
console.log(out);
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).connect(SSH);
|
||||
@@ -1,31 +0,0 @@
|
||||
module.paths.unshift('c:\\Users\\demo\\Downloads\\Deep Package Inspection\\node_modules');
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = { host: '103.185.47.52', port: 2222, username: 'adminbackend', password: 'htEo7x6LsBQiEHHH', readyTimeout: 60000 };
|
||||
|
||||
async function main() {
|
||||
const conn = new Client();
|
||||
await new Promise((resolve, reject) => {
|
||||
conn.on('ready', resolve).on('error', reject).connect(SSH);
|
||||
});
|
||||
console.log('SSH connected.');
|
||||
|
||||
const runCmd = (cmd) => {
|
||||
return new Promise((resolve) => {
|
||||
conn.exec(cmd, (err, stream) => {
|
||||
if (err) { resolve(`Err: ${err.message}`); return; }
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.stderr.on('data', d => out += d);
|
||||
stream.on('close', () => resolve(out.trim()));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const code = await runCmd('cat /home/adminbackend/web/demoplace.my.id/public_html/proxy/netifyClient.js');
|
||||
console.log(code);
|
||||
|
||||
conn.end();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,22 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
conn.exec("cat /home/adminbackend/web/demoplace.my.id/public_html/src/app/\\(dashboard\\)/agents/page.tsx", (err, stream) => {
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => {
|
||||
console.log('--- REMOTE FILE CONTENT ---');
|
||||
console.log(out);
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).connect(SSH);
|
||||
@@ -1,31 +0,0 @@
|
||||
module.paths.unshift('c:\\Users\\demo\\Downloads\\Deep Package Inspection\\node_modules');
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = { host: '103.185.47.52', port: 2222, username: 'adminbackend', password: 'htEo7x6LsBQiEHHH', readyTimeout: 60000 };
|
||||
|
||||
async function main() {
|
||||
const conn = new Client();
|
||||
await new Promise((resolve, reject) => {
|
||||
conn.on('ready', resolve).on('error', reject).connect(SSH);
|
||||
});
|
||||
console.log('SSH connected.');
|
||||
|
||||
const runCmd = (cmd) => {
|
||||
return new Promise((resolve) => {
|
||||
conn.exec(cmd, (err, stream) => {
|
||||
if (err) { resolve(`Err: ${err.message}`); return; }
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.stderr.on('data', d => out += d);
|
||||
stream.on('close', () => resolve(out.trim()));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const code = await runCmd('cat /home/adminbackend/web/demoplace.my.id/public_html/proxy/netifyTelemetry.js');
|
||||
console.log(code);
|
||||
|
||||
conn.end();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,22 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
conn.exec("cat /home/adminbackend/web/demoplace.my.id/public_html/start-with-env.js", (err, stream) => {
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => {
|
||||
console.log('--- start-with-env.js CONTENT ---');
|
||||
console.log(out);
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).connect(SSH);
|
||||
@@ -1,36 +0,0 @@
|
||||
module.paths.unshift('c:\\Users\\demo\\Downloads\\Deep Package Inspection\\node_modules');
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = { host: '103.185.47.52', port: 2222, username: 'adminbackend', password: 'htEo7x6LsBQiEHHH', readyTimeout: 60000 };
|
||||
|
||||
async function main() {
|
||||
const conn = new Client();
|
||||
await new Promise((resolve, reject) => {
|
||||
conn.on('ready', resolve).on('error', reject).connect(SSH);
|
||||
});
|
||||
console.log('SSH connected.');
|
||||
|
||||
const runCmd = (cmd) => {
|
||||
return new Promise((resolve) => {
|
||||
conn.exec(cmd, (err, stream) => {
|
||||
if (err) { resolve(`Err: ${err.message}`); return; }
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => resolve(out.trim()));
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const pm2List = await runCmd('pm2 list || npx pm2 list');
|
||||
console.log('=== PM2 LIST ===\n', pm2List);
|
||||
|
||||
const psAux = await runCmd('ps aux | grep node');
|
||||
console.log('\n=== PS AUX NODE ===\n', psAux);
|
||||
|
||||
const pwdInfo = await runCmd('ls -la /home/adminbackend/web/demoplace.my.id/public_html');
|
||||
console.log('\n=== PUBLIC_HTML DIR ===\n', pwdInfo.substring(0, 1000));
|
||||
|
||||
conn.end();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,44 +0,0 @@
|
||||
// test/run-remote-cmd.js
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const CONFIG = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
};
|
||||
|
||||
const cmd = process.argv.slice(2).join(' ') || 'ls -la';
|
||||
|
||||
function run() {
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
console.log(`[SSH] Connected. Running: "${cmd}"\n`);
|
||||
conn.exec(cmd, (err, stream) => {
|
||||
if (err) {
|
||||
console.error('Exec error:', err.message);
|
||||
conn.end();
|
||||
return;
|
||||
}
|
||||
stream.on('data', (data) => {
|
||||
process.stdout.write(data.toString());
|
||||
});
|
||||
stream.stderr.on('data', (data) => {
|
||||
process.stderr.write(data.toString());
|
||||
});
|
||||
stream.on('close', (code, signal) => {
|
||||
console.log(`\n[SSH] Command exited with code: ${code}`);
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).on('error', (err) => {
|
||||
console.error('SSH Error:', err.message);
|
||||
}).connect({
|
||||
host: CONFIG.host,
|
||||
port: CONFIG.port,
|
||||
username: CONFIG.username,
|
||||
password: CONFIG.password,
|
||||
});
|
||||
}
|
||||
|
||||
run();
|
||||
@@ -1,123 +0,0 @@
|
||||
const mongoose = require('../backend/node_modules/mongoose');
|
||||
const path = require('path');
|
||||
const bcrypt = require('bcryptjs');
|
||||
|
||||
require('dotenv').config({ path: path.join(__dirname, '../.env.local') });
|
||||
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/backone_dpi';
|
||||
|
||||
const User = require('../backend/models/User');
|
||||
const { TenantConfig, CustomAgentLocation } = require('../backend/models/Schemas');
|
||||
|
||||
async function run() {
|
||||
console.log('Connecting to MongoDB at:', MONGODB_URI);
|
||||
try {
|
||||
await mongoose.connect(MONGODB_URI);
|
||||
console.log('Connected successfully. Running seeding...');
|
||||
|
||||
// 1. Seed SIAB user
|
||||
const siabCount = await User.countDocuments({ username: 'siab' });
|
||||
if (siabCount === 0) {
|
||||
const hash = bcrypt.hashSync('siab', 10);
|
||||
await User.create({
|
||||
username: 'siab',
|
||||
password_hash: hash,
|
||||
account_name: 'SIAB Administrator',
|
||||
role: 'TENANT_ADMIN',
|
||||
site_uuid: '6681452d_9cae_4ff4_8ae8_0d504774265e',
|
||||
agent_uuid: null,
|
||||
});
|
||||
console.log('✓ Seeded SIAB Tenant User: siab / siab');
|
||||
} else {
|
||||
console.log('SIAB user already exists');
|
||||
}
|
||||
|
||||
// 2. Seed Nexus user
|
||||
const nexusCount = await User.countDocuments({ username: 'nexus' });
|
||||
if (nexusCount === 0) {
|
||||
const hash = bcrypt.hashSync('nexus', 10);
|
||||
await User.create({
|
||||
username: 'nexus',
|
||||
password_hash: hash,
|
||||
account_name: 'Nexus Administrator',
|
||||
role: 'TENANT_ADMIN',
|
||||
site_uuid: 'd7902405_0dc2_458b_8584_ed4d24b64f24',
|
||||
agent_uuid: null,
|
||||
});
|
||||
console.log('✓ Seeded Nexus Tenant User: nexus / nexus');
|
||||
} else {
|
||||
console.log('Nexus user already exists');
|
||||
}
|
||||
|
||||
// 3. Seed TenantConfigs
|
||||
const defaultConfigs = [
|
||||
{
|
||||
site_uuid: 'default',
|
||||
brand_name: 'BackOne',
|
||||
brand_logo: '/backone-logo.png',
|
||||
footer_copyright: 'PT. Data Bisnis Solusi',
|
||||
primary_color: '#E11D48',
|
||||
},
|
||||
{
|
||||
site_uuid: '6681452d_9cae_4ff4_8ae8_0d504774265e',
|
||||
brand_name: 'SIAB',
|
||||
brand_logo: '/siab-logo.png',
|
||||
footer_copyright: 'PT. Data Bisnis Solusi',
|
||||
primary_color: '#3B82F6',
|
||||
},
|
||||
{
|
||||
site_uuid: 'd7902405_0dc2_458b_8584_ed4d24b64f24',
|
||||
brand_name: 'Nexus',
|
||||
brand_logo: '/nexus-logo.png',
|
||||
footer_copyright: 'PT. Nexus Solusi',
|
||||
primary_color: '#8B5CF6',
|
||||
}
|
||||
];
|
||||
|
||||
for (const config of defaultConfigs) {
|
||||
await TenantConfig.findOneAndUpdate({ site_uuid: config.site_uuid }, config, { upsert: true });
|
||||
console.log(`✓ Seeded/Updated TenantConfig for: ${config.brand_name}`);
|
||||
}
|
||||
|
||||
// Seed default agent locations
|
||||
const defaultLocations = [
|
||||
{
|
||||
agent_uuid: 'F6-2V-DT-8A',
|
||||
site_uuid: '6681452d_9cae_4ff4_8ae8_0d504774265e',
|
||||
latitude: -6.2263304,
|
||||
longitude: 106.4247322,
|
||||
label: 'CPI Balaraja Agent Office'
|
||||
},
|
||||
{
|
||||
agent_uuid: '2F-TF-1D-GK',
|
||||
site_uuid: '6681452d_9cae_4ff4_8ae8_0d504774265e',
|
||||
latitude: -6.3763318,
|
||||
longitude: 106.8983017,
|
||||
label: 'JRP Cibubur Agent Office'
|
||||
},
|
||||
{
|
||||
agent_uuid: '8A-V3-PB-85',
|
||||
site_uuid: '6681452d_9cae_4ff4_8ae8_0d504774265e',
|
||||
latitude: -6.2253265,
|
||||
longitude: 106.8061484,
|
||||
label: 'IFG LT.18 Agent HQ'
|
||||
}
|
||||
];
|
||||
|
||||
for (const loc of defaultLocations) {
|
||||
const existing = await CustomAgentLocation.findOne({ agent_uuid: loc.agent_uuid });
|
||||
if (!existing) {
|
||||
await CustomAgentLocation.create(loc);
|
||||
console.log(`✓ Seeded CustomAgentLocation for: ${loc.agent_uuid}`);
|
||||
} else {
|
||||
console.log(`CustomAgentLocation for ${loc.agent_uuid} already exists`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('Seeding completed successfully!');
|
||||
await mongoose.disconnect();
|
||||
} catch (err) {
|
||||
console.error('Seeding error:', err);
|
||||
}
|
||||
}
|
||||
|
||||
run();
|
||||
@@ -1,197 +0,0 @@
|
||||
// test/sync_test.js
|
||||
// TDD Integration Test: Verifikasi sinkronisasi 100% file antara Localhost dan Domain
|
||||
'use strict';
|
||||
|
||||
const { Client } = require('ssh2');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
|
||||
// Load environment variables if available
|
||||
try {
|
||||
require('dotenv').config({ path: path.join(__dirname, '../.env.local') });
|
||||
} catch (e) {}
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const REMOTE_ROOT = '/home/adminbackend/web/demoplace.my.id/public_html';
|
||||
const LOCAL_ROOT = path.join(__dirname, '..');
|
||||
|
||||
let testCount = 0;
|
||||
let passedCount = 0;
|
||||
|
||||
function assert(label, condition) {
|
||||
testCount++;
|
||||
if (condition) {
|
||||
console.log(` ✓ PASSED: ${label}`);
|
||||
passedCount++;
|
||||
} else {
|
||||
console.error(` ✗ FAILED: ${label}`);
|
||||
}
|
||||
}
|
||||
|
||||
function getMD5(filePath) {
|
||||
try {
|
||||
const data = fs.readFileSync(filePath);
|
||||
return crypto.createHash('md5').update(data).digest('hex');
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function getFilesLocal(dir, files = []) {
|
||||
const list = fs.readdirSync(dir);
|
||||
for (const item of list) {
|
||||
const fullPath = path.join(dir, item);
|
||||
const stat = fs.statSync(fullPath);
|
||||
if (stat.isDirectory()) {
|
||||
if (item !== 'node_modules' && item !== '.next' && item !== '.git') {
|
||||
getFilesLocal(fullPath, files);
|
||||
}
|
||||
} else {
|
||||
files.push(path.relative(LOCAL_ROOT, fullPath).replace(/\\/g, '/'));
|
||||
}
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
const remoteScript = `
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
|
||||
const root = '/home/adminbackend/web/demoplace.my.id/public_html';
|
||||
|
||||
function getMD5(filePath) {
|
||||
try {
|
||||
const data = fs.readFileSync(filePath);
|
||||
return crypto.createHash('md5').update(data).digest('hex');
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function getFilesRemote(dir, files = {}) {
|
||||
try {
|
||||
const list = fs.readdirSync(dir);
|
||||
for (const item of list) {
|
||||
const fullPath = path.join(dir, item);
|
||||
const stat = fs.statSync(fullPath);
|
||||
if (stat.isDirectory()) {
|
||||
if (item !== 'node_modules' && item !== '.next' && item !== '.git') {
|
||||
getFilesRemote(fullPath, files);
|
||||
}
|
||||
} else {
|
||||
const rel = path.relative(root, fullPath);
|
||||
files[rel] = { md5: getMD5(fullPath), size: stat.size };
|
||||
}
|
||||
}
|
||||
} catch(e) {}
|
||||
return files;
|
||||
}
|
||||
|
||||
const filesMap = {};
|
||||
getFilesRemote(path.join(root, 'src'), filesMap);
|
||||
getFilesRemote(path.join(root, 'public'), filesMap);
|
||||
getFilesRemote(path.join(root, 'backend'), filesMap);
|
||||
getFilesRemote(path.join(root, 'proxy'), filesMap);
|
||||
|
||||
const rootConfigs = ['package.json', 'tsconfig.json', 'next.config.ts', '.env.production'];
|
||||
for (const f of rootConfigs) {
|
||||
const full = path.join(root, f);
|
||||
if (fs.existsSync(full)) {
|
||||
const stat = fs.statSync(full);
|
||||
filesMap[f] = { md5: getMD5(full), size: stat.size };
|
||||
}
|
||||
}
|
||||
|
||||
console.log(JSON.stringify(filesMap));
|
||||
`;
|
||||
|
||||
async function runTests() {
|
||||
console.log('\n=========================================');
|
||||
console.log(' RUNNING TDD SYNC COMPARISON TESTS');
|
||||
console.log('=========================================\n');
|
||||
|
||||
let remoteFiles = {};
|
||||
try {
|
||||
const conn = new Client();
|
||||
const remoteFilesStr = await new Promise((resolve, reject) => {
|
||||
conn.on('ready', () => {
|
||||
const b64 = Buffer.from(remoteScript).toString('base64');
|
||||
conn.exec(`echo "${b64}" | base64 -d | node`, (err, stream) => {
|
||||
if (err) return reject(err);
|
||||
let out = '';
|
||||
let errOut = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.stderr.on('data', d => errOut += d);
|
||||
stream.on('close', () => {
|
||||
conn.end();
|
||||
if (errOut.trim()) {
|
||||
reject(new Error(errOut));
|
||||
} else {
|
||||
resolve(out);
|
||||
}
|
||||
});
|
||||
});
|
||||
}).on('error', reject).connect(SSH);
|
||||
});
|
||||
|
||||
remoteFiles = JSON.parse(remoteFilesStr);
|
||||
console.log('✓ Connected to remote server and retrieved remote file list.');
|
||||
} catch (err) {
|
||||
console.error('✗ Failed to connect to remote server:', err.message);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Get local files
|
||||
const localFiles = {};
|
||||
const pathsToCheck = ['src', 'public', 'backend', 'proxy'];
|
||||
for (const p of pathsToCheck) {
|
||||
const full = path.join(LOCAL_ROOT, p);
|
||||
if (fs.existsSync(full)) {
|
||||
const files = getFilesLocal(full);
|
||||
for (const f of files) {
|
||||
const localPath = path.join(LOCAL_ROOT, f);
|
||||
localFiles[f] = { md5: getMD5(localPath) };
|
||||
}
|
||||
}
|
||||
}
|
||||
const rootConfigs = ['package.json', 'tsconfig.json', 'next.config.ts', '.env.production'];
|
||||
for (const f of rootConfigs) {
|
||||
const full = path.join(LOCAL_ROOT, f);
|
||||
if (fs.existsSync(full)) {
|
||||
localFiles[f] = { md5: getMD5(full) };
|
||||
}
|
||||
}
|
||||
|
||||
// Perform assertions
|
||||
for (const [relPath, info] of Object.entries(remoteFiles)) {
|
||||
const localInfo = localFiles[relPath];
|
||||
assert(`File "${relPath}" should exist locally`, !!localInfo);
|
||||
if (localInfo) {
|
||||
assert(`File "${relPath}" content should match remote exactly`, localInfo.md5 === info.md5);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`\n=========================================`);
|
||||
console.log(` RESULT: ${passedCount} / ${testCount} tests passed.`);
|
||||
console.log(`=========================================\n`);
|
||||
|
||||
if (passedCount !== testCount) {
|
||||
process.exit(1);
|
||||
} else {
|
||||
process.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
runTests().catch(e => {
|
||||
console.error('[FATAL]', e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,20 +0,0 @@
|
||||
const path = require('path');
|
||||
require('dotenv').config({ path: path.join(__dirname, '../.env.local') });
|
||||
|
||||
const { getAgents } = require('../src/lib/actions/agents');
|
||||
|
||||
async function main() {
|
||||
const siteUuid = '6681452d_9cae_4ff4_8ae8_0d504774265e';
|
||||
console.log('Calling getAgents with site_uuid:', siteUuid);
|
||||
try {
|
||||
const agents = await getAgents(siteUuid);
|
||||
console.log(`Returned ${agents.length} agents:`);
|
||||
agents.forEach(a => {
|
||||
console.log(`- ID: ${a.id}, UUID: ${a.uuid}, Label: ${a.label}, Status: ${a.last_seen_at?.human}`);
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Error:', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -1,32 +0,0 @@
|
||||
const axios = require('axios');
|
||||
|
||||
async function main() {
|
||||
console.log('Fetching /login HTML to find all asset paths...');
|
||||
const res = await axios.get('https://demoplace.my.id/login');
|
||||
const html = res.data;
|
||||
|
||||
// Extract all /_next/static/ paths
|
||||
const matches = html.match(/\/(_next|public)\/[a-zA-Z0-9_\-\.\/]+/g) || [];
|
||||
const uniquePaths = [...new Set(matches)];
|
||||
|
||||
console.log(`Found ${uniquePaths.length} unique asset paths to check:`);
|
||||
|
||||
let failed = 0;
|
||||
for (const assetPath of uniquePaths) {
|
||||
const url = `https://demoplace.my.id${assetPath}`;
|
||||
try {
|
||||
const assetRes = await axios.get(url);
|
||||
console.log(`✓ [200 OK] ${assetPath} (${assetRes.headers['content-length'] || assetRes.data.length} bytes)`);
|
||||
} catch (err) {
|
||||
console.error(`✗ [FAIL] ${assetPath}: ${err.message}`);
|
||||
failed++;
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`\n=== Verification Complete: ${uniquePaths.length - failed} passed, ${failed} failed ===`);
|
||||
if (failed > 0) {
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,28 +0,0 @@
|
||||
const axios = require('axios');
|
||||
|
||||
async function main() {
|
||||
console.log('Fetching /login HTML to find asset paths...');
|
||||
const res = await axios.get('https://demoplace.my.id/login');
|
||||
const html = res.data;
|
||||
|
||||
// Find a CSS asset path
|
||||
const cssMatch = html.match(/\/_next\/static\/chunks\/[a-zA-Z0-9_-]+\.css/);
|
||||
if (cssMatch) {
|
||||
const cssPath = cssMatch[0];
|
||||
console.log('Found CSS path:', cssPath);
|
||||
console.log('Fetching CSS asset from domain...');
|
||||
try {
|
||||
const cssRes = await axios.get(`https://demoplace.my.id${cssPath}`);
|
||||
console.log('CSS Status:', cssRes.status);
|
||||
console.log('CSS Content-Type:', cssRes.headers['content-type']);
|
||||
console.log('CSS Content-Length:', cssRes.headers['content-length']);
|
||||
console.log('CSS Content snippet:', cssRes.data.substring(0, 200));
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch CSS:', err.message);
|
||||
}
|
||||
} else {
|
||||
console.log('No CSS asset path match found in HTML!');
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,35 +0,0 @@
|
||||
// test/test-data-size-format.js
|
||||
const assert = require('assert');
|
||||
|
||||
function formatDataSize(sizeMB) {
|
||||
let displaySize = "";
|
||||
if (sizeMB >= 1024 * 1024) {
|
||||
displaySize = `${(sizeMB / (1024 * 1024)).toFixed(2)} TB`;
|
||||
} else if (sizeMB >= 1024) {
|
||||
displaySize = `${(sizeMB / 1024).toFixed(2)} GB`;
|
||||
} else {
|
||||
displaySize = `${sizeMB.toFixed(2)} MB`;
|
||||
}
|
||||
return displaySize;
|
||||
}
|
||||
|
||||
try {
|
||||
// Test case 1: Less than 1024 MB
|
||||
assert.strictEqual(formatDataSize(0.38), "0.38 MB");
|
||||
assert.strictEqual(formatDataSize(95.68), "95.68 MB");
|
||||
assert.strictEqual(formatDataSize(999.99), "999.99 MB");
|
||||
|
||||
// Test case 2: Over 1024 MB (GB)
|
||||
assert.strictEqual(formatDataSize(1024), "1.00 GB");
|
||||
assert.strictEqual(formatDataSize(1536), "1.50 GB");
|
||||
assert.strictEqual(formatDataSize(7654.67), "7.48 GB");
|
||||
|
||||
// Test case 3: Over 1024 * 1024 MB (TB)
|
||||
assert.strictEqual(formatDataSize(1048576), "1.00 TB");
|
||||
assert.strictEqual(formatDataSize(1572864), "1.50 TB");
|
||||
|
||||
console.log("✓ All Data Size formatting unit tests passed successfully!");
|
||||
} catch (err) {
|
||||
console.error("✗ Unit tests failed:", err.message);
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
const axios = require('axios');
|
||||
|
||||
async function main() {
|
||||
console.log('Logging in to remote server...');
|
||||
const loginRes = await axios.post('https://demoplace.my.id/api/auth/login', {
|
||||
username: 'admin',
|
||||
password: 'admin'
|
||||
});
|
||||
|
||||
const cookie = loginRes.headers['set-cookie'];
|
||||
const headers = {
|
||||
Cookie: cookie ? cookie.join('; ') : ''
|
||||
};
|
||||
|
||||
console.log('\n--- API: /api/auth/me ---');
|
||||
try {
|
||||
const res = await axios.get('https://demoplace.my.id/api/auth/me', { headers });
|
||||
console.log(JSON.stringify(res.data, null, 2));
|
||||
} catch (err) {
|
||||
console.error(err.message);
|
||||
}
|
||||
|
||||
console.log('\n--- API: /api/auth/admin/users ---');
|
||||
try {
|
||||
const res = await axios.get('https://demoplace.my.id/api/auth/admin/users', { headers });
|
||||
console.log(JSON.stringify(res.data, null, 2));
|
||||
} catch (err) {
|
||||
console.error(err.message);
|
||||
}
|
||||
|
||||
console.log('\n--- API: /api/dashboard/agents ---');
|
||||
try {
|
||||
const res = await axios.get('https://demoplace.my.id/api/dashboard/agents', { headers });
|
||||
console.log(JSON.stringify(res.data, null, 2));
|
||||
} catch (err) {
|
||||
console.error(err.message);
|
||||
}
|
||||
|
||||
console.log('\n--- API: /api/dashboard/agents/uptime ---');
|
||||
try {
|
||||
const res = await axios.get('https://demoplace.my.id/api/dashboard/agents/uptime', { headers });
|
||||
console.log(JSON.stringify(res.data, null, 2));
|
||||
} catch (err) {
|
||||
console.error(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,15 +0,0 @@
|
||||
const path = require('path');
|
||||
require('dotenv').config({ path: './.env.local' });
|
||||
const { netifyFetch } = require('../proxy/netifyClientCore');
|
||||
|
||||
async function main() {
|
||||
console.log('Testing netifyFetch...');
|
||||
console.log('API Key:', process.env.NETIFY_API_KEY);
|
||||
|
||||
const start = Date.now();
|
||||
const data = await netifyFetch('/lookup/applications', { settings_limit: 5 });
|
||||
console.log('Done in:', Date.now() - start, 'ms');
|
||||
console.log('Data:', data);
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,20 +0,0 @@
|
||||
const mongoose = require('mongoose');
|
||||
|
||||
async function main() {
|
||||
const LOCAL_URI = 'mongodb://127.0.0.1:27017/backone_dpi';
|
||||
await mongoose.connect(LOCAL_URI);
|
||||
const db = mongoose.connection.db;
|
||||
|
||||
const filter = { agent_uuid: { $ne: null } };
|
||||
|
||||
const results = await db.collection('summaries')
|
||||
.aggregate([
|
||||
{ $match: filter },
|
||||
{ $sort: { timestamp: -1 } },
|
||||
{ $group: { _id: '$agent_uuid', lastSeen: { $first: '$timestamp' }, label: { $first: '$agent_label' } } },
|
||||
]).toArray();
|
||||
|
||||
console.log('Aggregated agents without site filter:', results);
|
||||
await mongoose.disconnect();
|
||||
}
|
||||
main();
|
||||
@@ -1,239 +0,0 @@
|
||||
// Test suite for the inactivity timeout logic (TDD approach)
|
||||
// This script mocks React hooks and browser APIs to verify correct behavior of our session timeout logic.
|
||||
|
||||
const assert = require("assert");
|
||||
|
||||
console.log("=== RUNNING INACTIVITY TIMEOUT LOGIC TESTS ===");
|
||||
|
||||
// ─── Test Harness ─────────────────────────────────────────────────────────────
|
||||
class MockDocument {
|
||||
constructor() {
|
||||
this.visibilityState = "visible";
|
||||
this.listeners = {};
|
||||
}
|
||||
addEventListener(event, callback) {
|
||||
if (!this.listeners[event]) this.listeners[event] = [];
|
||||
this.listeners[event].push(callback);
|
||||
}
|
||||
removeEventListener(event, callback) {
|
||||
if (!this.listeners[event]) return;
|
||||
this.listeners[event] = this.listeners[event].filter(cb => cb !== callback);
|
||||
}
|
||||
trigger(event) {
|
||||
if (this.listeners[event]) {
|
||||
this.listeners[event].forEach(cb => cb());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class MockWindow {
|
||||
constructor() {
|
||||
this.listeners = {};
|
||||
this.location = { href: "" };
|
||||
}
|
||||
addEventListener(event, callback) {
|
||||
if (!this.listeners[event]) this.listeners[event] = [];
|
||||
this.listeners[event].push(callback);
|
||||
}
|
||||
removeEventListener(event, callback) {
|
||||
if (!this.listeners[event]) return;
|
||||
this.listeners[event] = this.listeners[event].filter(cb => cb !== callback);
|
||||
}
|
||||
trigger(event) {
|
||||
if (this.listeners[event]) {
|
||||
this.listeners[event].forEach(cb => cb());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Test Inactivity Logic Class ──────────────────────────────────────────────
|
||||
class InactivityTimeoutTester {
|
||||
constructor(options = {}) {
|
||||
this.timeoutSeconds = options.timeoutSeconds || 3600; // 1 hour
|
||||
this.warningSeconds = options.warningSeconds || 120; // 2 minutes
|
||||
this.showWarning = false;
|
||||
this.timeLeft = this.warningSeconds;
|
||||
this.isLoggedOut = false;
|
||||
this.lastActivity = Date.now();
|
||||
this.visibilityState = "visible";
|
||||
}
|
||||
|
||||
// Simulate user activity event
|
||||
onUserActivity(currentTime) {
|
||||
if (this.visibilityState === "visible") {
|
||||
this.lastActivity = currentTime || Date.now();
|
||||
this.showWarning = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Simulate tick (every second or arbitrary delay)
|
||||
tick(currentTime) {
|
||||
const elapsed = Math.floor((currentTime - this.lastActivity) / 1000);
|
||||
const remaining = this.timeoutSeconds - elapsed;
|
||||
|
||||
if (remaining <= 0) {
|
||||
this.isLoggedOut = true;
|
||||
this.showWarning = false;
|
||||
} else if (remaining <= this.warningSeconds) {
|
||||
this.timeLeft = remaining;
|
||||
this.showWarning = true;
|
||||
} else {
|
||||
this.showWarning = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Simulate returning to the tab
|
||||
onVisibilityChange(newVisibilityState, currentTime) {
|
||||
this.visibilityState = newVisibilityState;
|
||||
if (newVisibilityState === "visible") {
|
||||
const elapsed = Math.floor((currentTime - this.lastActivity) / 1000);
|
||||
const remaining = this.timeoutSeconds - elapsed;
|
||||
|
||||
if (remaining <= 0) {
|
||||
this.isLoggedOut = true;
|
||||
this.showWarning = false;
|
||||
} else if (remaining <= this.warningSeconds) {
|
||||
this.timeLeft = remaining;
|
||||
this.showWarning = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── TEST CASES ───────────────────────────────────────────────────────────────
|
||||
|
||||
function testResetActivityWhenVisible() {
|
||||
console.log("- Test: Reset activity timer when tab is visible");
|
||||
const tester = new InactivityTimeoutTester();
|
||||
const initialActivity = tester.lastActivity;
|
||||
|
||||
// Wait 10 seconds
|
||||
const timeAfter10s = initialActivity + 10000;
|
||||
tester.onUserActivity(timeAfter10s);
|
||||
|
||||
// Last activity should be updated
|
||||
assert.ok(tester.lastActivity >= initialActivity);
|
||||
}
|
||||
|
||||
function testNoResetActivityWhenHidden() {
|
||||
console.log("- Test: Do NOT reset activity timer when tab is hidden");
|
||||
const tester = new InactivityTimeoutTester();
|
||||
const initialActivity = tester.lastActivity;
|
||||
|
||||
// Change tab status to hidden
|
||||
tester.visibilityState = "hidden";
|
||||
|
||||
// User activity should be ignored for reset
|
||||
tester.onUserActivity(initialActivity + 10000);
|
||||
assert.strictEqual(tester.lastActivity, initialActivity);
|
||||
}
|
||||
|
||||
function testWarningThreshold() {
|
||||
console.log("- Test: Trigger warning at 2 minutes remaining");
|
||||
const tester = new InactivityTimeoutTester({ timeoutSeconds: 3600, warningSeconds: 120 });
|
||||
const start = Date.now();
|
||||
|
||||
// Tick at 59 minutes (3540 seconds elapsed, 60 seconds remaining)
|
||||
const warnTime = start + (3540 * 1000);
|
||||
tester.tick(warnTime);
|
||||
|
||||
assert.strictEqual(tester.showWarning, true);
|
||||
assert.strictEqual(tester.timeLeft, 60);
|
||||
}
|
||||
|
||||
function testSafeZoneAfterActivity() {
|
||||
console.log("- Test: Warning goes away when user becomes active");
|
||||
const tester = new InactivityTimeoutTester({ timeoutSeconds: 3600, warningSeconds: 120 });
|
||||
const start = Date.now();
|
||||
|
||||
// Tick at 3540 seconds (warning is shown)
|
||||
const warnTime = start + (3540 * 1000);
|
||||
tester.tick(warnTime);
|
||||
assert.strictEqual(tester.showWarning, true);
|
||||
|
||||
// User performs activity at warnTime
|
||||
tester.onUserActivity(warnTime);
|
||||
|
||||
// Tick immediately after activity (should be in safe zone)
|
||||
tester.tick(warnTime);
|
||||
assert.strictEqual(tester.showWarning, false);
|
||||
}
|
||||
|
||||
function testAutoLogout() {
|
||||
console.log("- Test: Auto-logout after 1 hour of total inactivity");
|
||||
const tester = new InactivityTimeoutTester({ timeoutSeconds: 3600, warningSeconds: 120 });
|
||||
const start = Date.now();
|
||||
|
||||
// Tick after 3601 seconds
|
||||
const expireTime = start + (3601 * 1000);
|
||||
tester.tick(expireTime);
|
||||
|
||||
assert.strictEqual(tester.isLoggedOut, true);
|
||||
assert.strictEqual(tester.showWarning, false);
|
||||
}
|
||||
|
||||
function testTabSwitchSilentlyTicks() {
|
||||
console.log("- Test: Switching tabs continues counting down silently");
|
||||
const tester = new InactivityTimeoutTester({ timeoutSeconds: 3600, warningSeconds: 120 });
|
||||
const start = Date.now();
|
||||
|
||||
// Switch tab away to hidden
|
||||
tester.onVisibilityChange("hidden", start);
|
||||
|
||||
// Tick 10 minutes (600s) later while hidden
|
||||
const tenMinsLater = start + (600 * 1000);
|
||||
tester.tick(tenMinsLater);
|
||||
|
||||
// Should still be in safe zone (no warning yet, no logout)
|
||||
assert.strictEqual(tester.showWarning, false);
|
||||
assert.strictEqual(tester.isLoggedOut, false);
|
||||
}
|
||||
|
||||
function testTabReturnImmediateCheck() {
|
||||
console.log("- Test: Tab return triggers immediate state check");
|
||||
const tester = new InactivityTimeoutTester({ timeoutSeconds: 3600, warningSeconds: 120 });
|
||||
const start = Date.now();
|
||||
|
||||
// User switches tab away
|
||||
tester.onVisibilityChange("hidden", start);
|
||||
|
||||
// User is away for 59 minutes (3540s), then returns
|
||||
const returnTime = start + (3540 * 1000);
|
||||
tester.onVisibilityChange("visible", returnTime);
|
||||
|
||||
// Should immediately show warning with remaining time of 60 seconds
|
||||
assert.strictEqual(tester.showWarning, true);
|
||||
assert.strictEqual(tester.timeLeft, 60);
|
||||
}
|
||||
|
||||
function testTabReturnExpiredLogout() {
|
||||
console.log("- Test: Tab return logs out immediately if expired while away");
|
||||
const tester = new InactivityTimeoutTester({ timeoutSeconds: 3600, warningSeconds: 120 });
|
||||
const start = Date.now();
|
||||
|
||||
// User switches tab away
|
||||
tester.onVisibilityChange("hidden", start);
|
||||
|
||||
// User is away for 61 minutes (3660s), then returns
|
||||
const returnTime = start + (3660 * 1000);
|
||||
tester.onVisibilityChange("visible", returnTime);
|
||||
|
||||
// Should immediately trigger logout
|
||||
assert.strictEqual(tester.isLoggedOut, true);
|
||||
}
|
||||
|
||||
// Execute tests
|
||||
try {
|
||||
testResetActivityWhenVisible();
|
||||
testNoResetActivityWhenHidden();
|
||||
testWarningThreshold();
|
||||
testSafeZoneAfterActivity();
|
||||
testAutoLogout();
|
||||
testTabSwitchSilentlyTicks();
|
||||
testTabReturnImmediateCheck();
|
||||
testTabReturnExpiredLogout();
|
||||
console.log("✓ ALL TESTS PASSED SUCCESSFULLY!");
|
||||
} catch (error) {
|
||||
console.error("❌ TEST FAILURE:", error);
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
const { netifyFetch } = require('../proxy/netifyClientCore');
|
||||
require('dotenv').config({ path: './.env.local' });
|
||||
|
||||
async function main() {
|
||||
console.log('Fetching with limit 5000...');
|
||||
const start = Date.now();
|
||||
const data = await netifyFetch('/lookup/applications', { settings_limit: 5000 });
|
||||
console.log('Done in:', Date.now() - start, 'ms');
|
||||
console.log('Returned items count:', data?.length);
|
||||
if (data && data.length > 0) {
|
||||
console.log('First item:', data[0].id, data[0].name);
|
||||
console.log('Last item:', data[data.length - 1].id, data[data.length - 1].name);
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,30 +0,0 @@
|
||||
const axios = require('axios');
|
||||
|
||||
async function main() {
|
||||
console.log('Logging in to localhost...');
|
||||
const loginRes = await axios.post('http://localhost:3001/api/auth/login', {
|
||||
username: 'admin',
|
||||
password: 'admin'
|
||||
});
|
||||
|
||||
const cookie = loginRes.headers['set-cookie'];
|
||||
console.log('Login successful. Cookies:', cookie);
|
||||
|
||||
console.log('Fetching /api/auth/me...');
|
||||
const meRes = await axios.get('http://localhost:3001/api/auth/me', {
|
||||
headers: {
|
||||
Cookie: cookie ? cookie.join('; ') : ''
|
||||
}
|
||||
});
|
||||
console.log('/api/auth/me response:', meRes.data);
|
||||
|
||||
console.log('Fetching /api/auth/admin/users...');
|
||||
const usersRes = await axios.get('http://localhost:3001/api/auth/admin/users', {
|
||||
headers: {
|
||||
Cookie: cookie ? cookie.join('; ') : ''
|
||||
}
|
||||
});
|
||||
console.log('/api/auth/admin/users response:', usersRes.data);
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,24 +0,0 @@
|
||||
const axios = require('axios');
|
||||
|
||||
async function main() {
|
||||
console.log('Logging in to localhost Next.js server on port 3000...');
|
||||
const loginRes = await axios.post('http://localhost:3000/api/auth/login', {
|
||||
username: 'admin',
|
||||
password: 'admin'
|
||||
});
|
||||
|
||||
const cookie = loginRes.headers['set-cookie'];
|
||||
const headers = {
|
||||
Cookie: cookie ? cookie.join('; ') : ''
|
||||
};
|
||||
|
||||
console.log('Fetching localhost /api/auth/admin/users...');
|
||||
const res = await axios.get('http://localhost:3000/api/auth/admin/users', { headers });
|
||||
console.log('Total users returned:', res.data.data.length);
|
||||
console.log('Users list:');
|
||||
res.data.data.forEach(u => {
|
||||
console.log(`- Username: ${u.username}, Role: ${u.role}, Site: ${u.site_uuid}`);
|
||||
});
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,6 +0,0 @@
|
||||
const rootMongoose = require('mongoose');
|
||||
const proxyMongoose = require('../proxy/node_modules/mongoose');
|
||||
|
||||
console.log('Root Mongoose === Proxy Mongoose:', rootMongoose === proxyMongoose);
|
||||
console.log('Root Mongoose version:', rootMongoose.version);
|
||||
console.log('Proxy Mongoose version:', proxyMongoose.version);
|
||||
@@ -1,12 +0,0 @@
|
||||
const { netifyFetch } = require('../proxy/netifyClientCore');
|
||||
require('dotenv').config({ path: './.env.local' });
|
||||
|
||||
async function main() {
|
||||
const p1 = await netifyFetch('/lookup/applications', { settings_limit: 5, settings_page: 1 });
|
||||
const p2 = await netifyFetch('/lookup/applications', { settings_limit: 5, settings_page: 2 });
|
||||
|
||||
console.log('Page 1 items:', p1.map(x => ({ id: x.id, name: x.name })));
|
||||
console.log('Page 2 items:', p2.map(x => ({ id: x.id, name: x.name })));
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,18 +0,0 @@
|
||||
const { netifyFetch } = require('../proxy/netifyClientCore');
|
||||
require('dotenv').config({ path: './.env.local' });
|
||||
|
||||
async function main() {
|
||||
const p1 = await netifyFetch('/lookup/applications', { settings_limit: 5, settings_page: 1 });
|
||||
const p2 = await netifyFetch('/lookup/applications', { settings_limit: 5, settings_page: 2 });
|
||||
|
||||
console.log('Page 1 length:', p1?.length);
|
||||
console.log('Page 2 length:', p2?.length);
|
||||
if (p1 && p1.length > 0) {
|
||||
console.log('Page 1 first item:', p1[0].id, p1[0].name);
|
||||
}
|
||||
if (p2 && p2.length > 0) {
|
||||
console.log('Page 2 first item:', p2[0].id, p2[0].name);
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,16 +0,0 @@
|
||||
const mongoose = require('mongoose');
|
||||
|
||||
async function main() {
|
||||
const uri = 'mongodb://127.0.0.1:27017/backone_dpi';
|
||||
await mongoose.connect(uri);
|
||||
|
||||
const count = await mongoose.connection.db.collection('lookupapps').countDocuments({});
|
||||
console.log('Count inside reader:', count);
|
||||
|
||||
const doc = await mongoose.connection.db.collection('lookupapps').findOne({ id: 99999 });
|
||||
console.log('Found document:', doc);
|
||||
|
||||
await mongoose.disconnect();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,38 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
|
||||
const SSH = {
|
||||
host: '103.185.47.52',
|
||||
port: 2222,
|
||||
username: 'adminbackend',
|
||||
password: 'htEo7x6LsBQiEHHH',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const remoteJs = `
|
||||
const net = require('net');
|
||||
const s = net.createConnection(27017, 'mongodb.prod.proit.id', () => {
|
||||
console.log('SUCCESS: Connected to mongodb.prod.proit.id from remote server!');
|
||||
s.destroy();
|
||||
}).on('error', e => {
|
||||
console.error('FAILED: ' + e.message);
|
||||
});
|
||||
`;
|
||||
|
||||
const conn = new Client();
|
||||
conn.on('ready', () => {
|
||||
const b64 = Buffer.from(remoteJs).toString('base64');
|
||||
conn.exec(`echo "${b64}" | base64 -d | node`, (err, stream) => {
|
||||
if (err) {
|
||||
console.error(err);
|
||||
conn.end();
|
||||
return;
|
||||
}
|
||||
let out = '';
|
||||
stream.on('data', d => out += d);
|
||||
stream.on('close', () => {
|
||||
console.log('Result from remote:');
|
||||
console.log(out.trim());
|
||||
conn.end();
|
||||
});
|
||||
});
|
||||
}).on('error', console.error).connect(SSH);
|
||||
@@ -1,61 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
const net = require('net');
|
||||
const { MongoClient } = require('mongodb');
|
||||
|
||||
const sshConfig = {
|
||||
host: process.env.SSH_HOST || '127.0.0.1',
|
||||
port: parseInt(process.env.SSH_PORT || '2222'),
|
||||
username: process.env.SSH_USER || 'adminbackend',
|
||||
password: process.env.SSH_PASSWORD || '',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const LOCAL_PORT = 27019;
|
||||
const REMOTE_MONGO_HOST = 'mongodb.prod.proit.id';
|
||||
const REMOTE_MONGO_PORT = 27017;
|
||||
|
||||
const conn = new Client();
|
||||
const server = net.createServer((sock) => {
|
||||
conn.forwardOut(
|
||||
'127.0.0.1',
|
||||
sock.remotePort,
|
||||
REMOTE_MONGO_HOST,
|
||||
REMOTE_MONGO_PORT,
|
||||
(err, stream) => {
|
||||
if (err) {
|
||||
sock.destroy();
|
||||
return;
|
||||
}
|
||||
sock.pipe(stream);
|
||||
stream.pipe(sock);
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
conn.on('ready', () => {
|
||||
server.listen(LOCAL_PORT, '127.0.0.1', async () => {
|
||||
console.log(`SSH Tunnel established on port ${LOCAL_PORT}`);
|
||||
try {
|
||||
const REMOTE_URI = process.env.MONGODB_URI || `mongodb://backone_user:password@127.0.0.1:${LOCAL_PORT}/backone_dpi?authSource=backone_dpi&directConnection=true`;
|
||||
const client = new MongoClient(REMOTE_URI, { serverSelectionTimeoutMS: 5000 });
|
||||
await client.connect();
|
||||
const db = client.db('backone_dpi');
|
||||
console.log('Connected to remote database.');
|
||||
const collections = await db.listCollections().toArray();
|
||||
console.log('\nCollections and document counts:');
|
||||
for (const col of collections) {
|
||||
const count = await db.collection(col.name).countDocuments({});
|
||||
console.log(`- ${col.name}: ${count} documents`);
|
||||
}
|
||||
await client.close();
|
||||
} catch (e) {
|
||||
console.error('Error:', e.message);
|
||||
} finally {
|
||||
server.close();
|
||||
conn.end();
|
||||
console.log('Tunnel closed.');
|
||||
}
|
||||
});
|
||||
}).on('error', (err) => {
|
||||
console.error('SSH Error:', err.message);
|
||||
}).connect(sshConfig);
|
||||
@@ -1,61 +0,0 @@
|
||||
const { Client } = require('ssh2');
|
||||
const net = require('net');
|
||||
const { MongoClient } = require('mongodb');
|
||||
|
||||
const sshConfig = {
|
||||
host: process.env.SSH_HOST || '127.0.0.1',
|
||||
port: parseInt(process.env.SSH_PORT || '2222'),
|
||||
username: process.env.SSH_USER || 'adminbackend',
|
||||
password: process.env.SSH_PASSWORD || '',
|
||||
readyTimeout: 60000
|
||||
};
|
||||
|
||||
const LOCAL_PORT = 27019; // use 27019 to avoid conflicts
|
||||
const REMOTE_MONGO_HOST = 'mongodb.prod.proit.id';
|
||||
const REMOTE_MONGO_PORT = 27017;
|
||||
|
||||
const conn = new Client();
|
||||
const server = net.createServer((sock) => {
|
||||
conn.forwardOut(
|
||||
'127.0.0.1',
|
||||
sock.remotePort,
|
||||
REMOTE_MONGO_HOST,
|
||||
REMOTE_MONGO_PORT,
|
||||
(err, stream) => {
|
||||
if (err) {
|
||||
sock.destroy();
|
||||
return;
|
||||
}
|
||||
sock.pipe(stream);
|
||||
stream.pipe(sock);
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
conn.on('ready', () => {
|
||||
server.listen(LOCAL_PORT, '127.0.0.1', async () => {
|
||||
console.log(`SSH Tunnel established on port ${LOCAL_PORT}`);
|
||||
try {
|
||||
const REMOTE_URI = process.env.MONGODB_URI || `mongodb://backone_user:password@127.0.0.1:${LOCAL_PORT}/backone_dpi?authSource=backone_dpi`;
|
||||
const client = new MongoClient(REMOTE_URI, { serverSelectionTimeoutMS: 5000 });
|
||||
await client.connect();
|
||||
const db = client.db('backone_dpi');
|
||||
console.log('Connected to remote database.');
|
||||
const collections = await db.listCollections().toArray();
|
||||
console.log('\nCollections and document counts:');
|
||||
for (const col of collections) {
|
||||
const count = await db.collection(col.name).countDocuments({});
|
||||
console.log(`- ${col.name}: ${count} documents`);
|
||||
}
|
||||
await client.close();
|
||||
} catch (e) {
|
||||
console.error('Error:', e.message);
|
||||
} finally {
|
||||
server.close();
|
||||
conn.end();
|
||||
console.log('Tunnel closed.');
|
||||
}
|
||||
});
|
||||
}).on('error', (err) => {
|
||||
console.error('SSH Error:', err.message);
|
||||
}).connect(sshConfig);
|
||||
Loaded 100 of 189 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user