diff --git a/backend/check.js b/backend/check.js deleted file mode 100644 index 36ca026..0000000 --- a/backend/check.js +++ /dev/null @@ -1,10 +0,0 @@ -const mongoose = require('mongoose'); -async function check() { - await mongoose.connect('mongodb://backone_inspect:backone_inspect@mongodb.prod.proit.id:27017/backone_inspect_0'); - const t = await mongoose.connection.collection('threats').countDocuments({}); - console.log('Threats count:', t); - const events = await mongoose.connection.collection('events').countDocuments({}); - console.log('Events count:', events); - process.exit(0); -} -check(); diff --git a/backend/checkThreats.js b/backend/checkThreats.js deleted file mode 100644 index ec1be43..0000000 --- a/backend/checkThreats.js +++ /dev/null @@ -1,8 +0,0 @@ -const mongoose = require('mongoose'); -async function check() { - await mongoose.connect('mongodb://backone_inspect:backone_inspect@mongodb.prod.proit.id:27017/backone_inspect_0'); - const t = await mongoose.connection.collection('threats').find({}).toArray(); - console.log(JSON.stringify(t, null, 2)); - process.exit(0); -} -check(); diff --git a/backend/check_agent_countries.js b/backend/check_agent_countries.js deleted file mode 100644 index 5c90370..0000000 --- a/backend/check_agent_countries.js +++ /dev/null @@ -1,10 +0,0 @@ -const mongoose = require('mongoose'); -mongoose.connect('mongodb://backone_inspect:backone_inspect@mongodb.prod.proit.id:27017/backone_inspect_0') - .then(async (m) => { - const result = await m.connection.db.collection('countrystats').aggregate([ - { $match: { agent_uuid: '2F-TF-1D-GK' } }, - { $group: { _id: '$country_code' } } - ]).toArray(); - console.log('Countries for 2F-TF-1D-GK:', result); - process.exit(0); - }); diff --git a/backend/check_agent_dstips.js b/backend/check_agent_dstips.js deleted file mode 100644 index 9aa8b95..0000000 --- a/backend/check_agent_dstips.js +++ /dev/null @@ -1,11 +0,0 @@ -const mongoose = require('mongoose'); -mongoose.connect('mongodb://backone_inspect:backone_inspect@mongodb.prod.proit.id:27017/backone_inspect_0') - .then(async (m) => { - const result = await m.connection.db.collection('flows').aggregate([ - { $match: { agent_uuid: '2F-TF-1D-GK' } }, - { $group: { _id: '$dst_ip' } }, - { $limit: 10 } - ]).toArray(); - console.log('Flows dst_ips for 2F-TF-1D-GK:', result); - process.exit(0); - }); diff --git a/backend/check_apps_data.js b/backend/check_apps_data.js deleted file mode 100644 index fe9d985..0000000 --- a/backend/check_apps_data.js +++ /dev/null @@ -1,31 +0,0 @@ -const mongoose = require('mongoose'); -mongoose.connect('mongodb://backone_inspect:backone_inspect@mongodb.prod.proit.id:27017/backone_inspect_0') - .then(async (m) => { - const pipeline = [ - { $group: { - _id: '$app_label', - download: { $sum: '$download' }, - upload: { $sum: '$upload' }, - flows: { $sum: '$flows' }, - }}, - { $sort: { download: -1 } }, - { $limit: 3 } - ]; - let result = await m.connection.db.collection('appstats').aggregate(pipeline).toArray(); - if (result.length === 0) { - console.log('Falling back to flows...'); - result = await m.connection.db.collection('flows').aggregate([ - { $match: { app_label: { $ne: null, $ne: '' } } }, - { $group: { - _id: '$app_label', - download: { $sum: '$download' }, - upload: { $sum: '$upload' }, - flows: { $sum: 1 }, - }}, - { $sort: { download: -1 } }, - { $limit: 3 } - ]).toArray(); - } - console.log(result); - process.exit(0); - }); diff --git a/backend/check_appstats.js b/backend/check_appstats.js deleted file mode 100644 index 9d471bc..0000000 --- a/backend/check_appstats.js +++ /dev/null @@ -1,7 +0,0 @@ -const mongoose = require('mongoose'); -mongoose.connect('mongodb://backone_inspect:backone_inspect@mongodb.prod.proit.id:27017/backone_inspect_0') - .then(async (m) => { - const f = await m.connection.db.collection('appstats').find().sort({timestamp: -1}).limit(2).toArray(); - console.log('AppStats:', f); - process.exit(0); - }); diff --git a/backend/check_countries.js b/backend/check_countries.js deleted file mode 100644 index 0e9a9bb..0000000 --- a/backend/check_countries.js +++ /dev/null @@ -1,10 +0,0 @@ -const mongoose = require('mongoose'); -mongoose.connect('mongodb://backone_inspect:backone_inspect@mongodb.prod.proit.id:27017/backone_inspect_0') - .then(async (m) => { - const result = await m.connection.db.collection('countrystats').aggregate([ - { $group: { _id: '$country_name', download: { $sum: '$download' } } }, - { $sort: { download: -1 } } - ]).toArray(); - console.log(result); - process.exit(0); - }); diff --git a/backend/check_db.js b/backend/check_db.js deleted file mode 100644 index ac6f6e7..0000000 --- a/backend/check_db.js +++ /dev/null @@ -1,24 +0,0 @@ -const mongoose = require('mongoose'); -const path = require('path'); -require('dotenv').config({ path: path.join(__dirname, '..', '.env.local') }); - -async function checkDb() { - await mongoose.connect(process.env.MONGODB_URI); - const db = mongoose.connection.db; - - const apps = await db.collection('app_stats').countDocuments(); - console.log('Apps records:', apps); - - const protos = await db.collection('protocol_stats').countDocuments(); - console.log('Protocols records:', protos); - - const countries = await db.collection('country_stats').countDocuments(); - console.log('Country records:', countries); - - const agents = await db.collection('agent_registry').find().toArray(); - console.log('Agents:', agents.map(a => ({uuid: a.uuid, label: a.label, activated: a.activated, last_seen_at: a.last_seen_at}))); - - process.exit(0); -} - -checkDb().catch(console.error); diff --git a/backend/check_flows_data.js b/backend/check_flows_data.js deleted file mode 100644 index b811d2b..0000000 --- a/backend/check_flows_data.js +++ /dev/null @@ -1,18 +0,0 @@ -const mongoose = require('mongoose'); -mongoose.connect('mongodb://backone_inspect:backone_inspect@mongodb.prod.proit.id:27017/backone_inspect_0') - .then(async (m) => { - console.log('Aggregating flows...'); - const result = await m.connection.db.collection('flows').aggregate([ - { $match: { app_label: { $ne: null, $ne: '' } } }, - { $group: { - _id: '$app_label', - download: { $sum: '$download' }, - upload: { $sum: '$upload' }, - flows: { $sum: 1 }, - }}, - { $sort: { download: -1 } }, - { $limit: 3 } - ]).toArray(); - console.log(result); - process.exit(0); - }); diff --git a/backend/check_registry.js b/backend/check_registry.js deleted file mode 100644 index 2d87608..0000000 --- a/backend/check_registry.js +++ /dev/null @@ -1,7 +0,0 @@ -const mongoose = require('mongoose'); -mongoose.connect('mongodb://backone_inspect:backone_inspect@mongodb.prod.proit.id:27017/backone_inspect_0') - .then(async (m) => { - const agents = await m.connection.db.collection('agent_registry').find({}, {projection:{uuid:1, _id:0}}).toArray(); - console.log('Agents in registry:', agents.map(a => a.uuid)); - process.exit(0); - }); diff --git a/backend/check_registry_sites.js b/backend/check_registry_sites.js deleted file mode 100644 index ceb7470..0000000 --- a/backend/check_registry_sites.js +++ /dev/null @@ -1,7 +0,0 @@ -const mongoose = require('mongoose'); -mongoose.connect('mongodb://backone_inspect:backone_inspect@mongodb.prod.proit.id:27017/backone_inspect_0') - .then(async (m) => { - const agents = await m.connection.db.collection('agent_registry').find({}, {projection:{uuid:1, site_uuid:1, _id:0}}).toArray(); - console.log('Agents in registry:', agents); - process.exit(0); - }); diff --git a/backend/check_users.js b/backend/check_users.js deleted file mode 100644 index faf2ff1..0000000 --- a/backend/check_users.js +++ /dev/null @@ -1,7 +0,0 @@ -const mongoose = require('mongoose'); -mongoose.connect('mongodb://backone_inspect:backone_inspect@mongodb.prod.proit.id:27017/backone_inspect_0') - .then(async (m) => { - const users = await m.connection.db.collection('users').find({role: 'AGENT_VIEWER'}).toArray(); - console.log('AGENT_VIEWER users:', users); - process.exit(0); - }); diff --git a/backend/cleanup_contaminated.js b/backend/cleanup_contaminated.js deleted file mode 100644 index 950cb6b..0000000 --- a/backend/cleanup_contaminated.js +++ /dev/null @@ -1,79 +0,0 @@ -/** - * cleanup_contaminated_devices.js - * Hapus record device/flow yang terkontaminasi berdasarkan konfigurasi subnet - * dari agent_registry. Jalankan SETELAH mengisi subnet di UI Agents. - */ -const mongoose = require('mongoose'); - -async function cleanup() { - await mongoose.connect('mongodb://backone_inspect:backone_inspect@mongodb.prod.proit.id:27017/backone_inspect_0'); - console.log("Connected to MongoDB.\n"); - - const agents = await mongoose.connection.collection('agent_registry').find({}).toArray(); - - let totalDevicesDeleted = 0; - let totalFlowsDeleted = 0; - - for (const agent of agents) { - const uuid = agent.uuid; - const subnets = (agent.allowed_subnets || []).map(s => s.trim()).filter(Boolean); - - if (subnets.length === 0) { - console.log(`[${uuid}] Tidak ada subnet dikonfigurasi — skip.`); - continue; - } - - console.log(`[${uuid}] Subnet diizinkan: ${subnets.join(', ')}`); - - // Fungsi helper CIDR - const ipToLong = (ip) => ip.split('.').reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0) >>> 0; - const ipMatchesSubnets = (ip, subnets) => { - if (!subnets || subnets.length === 0) return true; - if (!ip) return false; - return subnets.some(subnet => { - if (subnet.includes('/')) { - try { - const [range, bitsStr] = subnet.split('/'); - const bits = parseInt(bitsStr, 10); - if (isNaN(bits) || bits < 0 || bits > 32) return false; - const mask = bits === 0 ? 0 : (~0 << (32 - bits)) >>> 0; - return (ipToLong(ip) & mask) === (ipToLong(range) & mask); - } catch (e) { - return false; - } - } - return ip.startsWith(subnet + '.') || ip === subnet; - }); - }; - - // Ambil semua IP dari agent ini - const ips = await mongoose.connection.collection('devicestats').distinct('ip_address', { agent_uuid: uuid }); - const invalidIps = ips.filter(ip => !ipMatchesSubnets(ip, subnets)); - - if (invalidIps.length > 0) { - const devResult = await mongoose.connection.collection('devicestats').deleteMany({ - agent_uuid: uuid, - ip_address: { $in: invalidIps } - }); - console.log(` → Hapus ${devResult.deletedCount} device records (IP tidak valid)`); - totalDevicesDeleted += devResult.deletedCount; - - const flowResult = await mongoose.connection.collection('flows').deleteMany({ - agent_uuid: uuid, - src_ip: { $in: invalidIps } - }); - console.log(` → Hapus ${flowResult.deletedCount} flow records (src_ip tidak valid)`); - totalFlowsDeleted += flowResult.deletedCount; - } else { - console.log(` → Tidak ada kontaminasi ditemukan.`); - } - console.log(); - } - - console.log(`\n===== SELESAI =====`); - console.log(`Total device records dihapus: ${totalDevicesDeleted}`); - console.log(`Total flow records dihapus : ${totalFlowsDeleted}`); - process.exit(0); -} - -cleanup().catch(e => { console.error(e.message); process.exit(1); }); diff --git a/backend/drop.js b/backend/drop.js deleted file mode 100644 index e86ed2d..0000000 --- a/backend/drop.js +++ /dev/null @@ -1,11 +0,0 @@ -const mongoose = require('mongoose'); - -async function drop() { - await mongoose.connect('mongodb://backone_inspect:backone_inspect@mongodb.prod.proit.id:27017/backone_inspect_0'); - await mongoose.connection.collection('summaries').deleteMany({}); - await mongoose.connection.collection('app_stats').deleteMany({}); - console.log('Dropped Summary and AppStat collections'); - process.exit(0); -} - -drop().catch(console.error); diff --git a/backend/middleware/auth.js b/backend/middleware/auth.js index 9868b64..e17ce9d 100644 --- a/backend/middleware/auth.js +++ b/backend/middleware/auth.js @@ -49,13 +49,17 @@ async function requireAuth(req, res, next) { } let targetUserDoc = null; - if (viewDecoded.target_user_id) { + if (viewDecoded.target_user_id && typeof viewDecoded.target_user_id === 'string') { targetUserDoc = await User.findById(viewDecoded.target_user_id).lean(); - } else if (viewDecoded.target_username) { + } else if (viewDecoded.target_username && typeof viewDecoded.target_username === 'string') { targetUserDoc = await User.findOne({ username: viewDecoded.target_username }).lean(); } else { targetUserDoc = await User.findOne({ agent_uuid: targetAgent, role: 'AGENT_VIEWER' }).lean(); } + + if (targetUserDoc && targetUserDoc.role === 'SUPER_ADMIN' && req.user.role !== 'SUPER_ADMIN') { + throw new Error('Forbidden view-as target role'); + } let targetSiteUuid = req.user.site_uuid; if (targetUserDoc && targetUserDoc.site_uuid) { diff --git a/backend/routes/auth/core.js b/backend/routes/auth/core.js index 1286453..de8a474 100644 --- a/backend/routes/auth/core.js +++ b/backend/routes/auth/core.js @@ -16,12 +16,12 @@ seedAuth(); // ─── POST /api/auth/login ───────────────────────────────────────────────────── router.post('/login', async (req, res) => { try { - const { username, password } = req.body; - if (!username || !password) { + const { username, password } = req.body || {}; + if (!username || !password || typeof username !== 'string' || typeof password !== 'string') { return res.status(400).json({ error: 'Username and password are required' }); } - const user = await User.findOne({ username, is_active: true }).select('+password_hash'); + const user = await User.findOne({ username: username.trim(), is_active: true }).select('+password_hash'); if (!user) { return res.status(401).json({ error: 'Username not found' }); } @@ -173,9 +173,11 @@ router.post('/logout', requireAuth, async (req, res) => { }); // ─── GET /api/auth/geoip?ip=x.x.x.x ───────────────────────────────────────── -router.get('/geoip', async (req, res) => { - const ip = req.query.ip; - if (!ip) return res.status(400).json({ error: 'IP is required' }); +router.get('/geoip', requireAuth, async (req, res) => { + const ip = typeof req.query.ip === 'string' ? req.query.ip.trim() : ''; + if (!ip || !/^[0-9a-fA-F:.]{2,45}$/.test(ip)) { + return res.status(400).json({ error: 'Valid IP is required' }); + } const parts = ip.split('.'); if (parts.length === 4) { diff --git a/backend/routes/auth/helpers.js b/backend/routes/auth/helpers.js index 2f9a446..d56c643 100644 --- a/backend/routes/auth/helpers.js +++ b/backend/routes/auth/helpers.js @@ -48,8 +48,15 @@ const storage = multer.diskStorage({ cb(null, dir); }, filename: (req, file, cb) => { + const mimeToExt = { + 'image/jpeg': '.jpg', + 'image/jpg': '.jpg', + 'image/png': '.png', + 'image/webp': '.webp', + }; + const safeExt = mimeToExt[file.mimetype] || '.png'; const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1e9)}`; - cb(null, `profile-${uniqueSuffix}${path.extname(file.originalname)}`); + cb(null, `profile-${uniqueSuffix}${safeExt}`); } }); diff --git a/backend/routes/auth/sessions.js b/backend/routes/auth/sessions.js index b9bc71f..d6be5f6 100644 --- a/backend/routes/auth/sessions.js +++ b/backend/routes/auth/sessions.js @@ -68,14 +68,18 @@ router.get('/admin/sessions', requireAdmin, async (req, res) => { try { let userQuery = {}; if (req.adminUser.role === 'TENANT_ADMIN') { - userQuery = { site_uuid: req.adminUser.site_uuid }; + userQuery = { site_uuid: req.adminUser.site_uuid, role: { $ne: 'SUPER_ADMIN' } }; + } else if (req.adminUser.role === 'COMPANY_ADMIN' || req.adminUser.role === 'COMPANY_OPERATOR') { + userQuery = { company_name: req.adminUser.company_name, role: { $ne: 'SUPER_ADMIN' } }; + } else if (req.adminUser.role === 'SOC_ANALYST') { + userQuery = { role: { $ne: 'SUPER_ADMIN' } }; } - const users = await User.find(userQuery, 'username role account_name site_uuid'); + const users = await User.find(userQuery, 'username role account_name site_uuid company_name'); const userIds = users.map(u => u._id); const sessions = await Session.find({ user_id: { $in: userIds } }) - .populate('user_id', 'username role account_name site_uuid') + .populate('user_id', 'username role account_name site_uuid company_name') .sort({ last_active: -1 }); const data = sessions.map(s => { @@ -103,14 +107,26 @@ router.get('/admin/sessions', requireAdmin, async (req, res) => { // ─── DELETE /api/auth/admin/sessions/:id (Revoke Any Session by Admin) ─────── router.delete('/admin/sessions/:id', requireAdmin, blockAnalyst, async (req, res) => { try { + if (req.adminUser.role === 'COMPANY_OPERATOR') { + return res.status(403).json({ ok: false, error: 'Aksi ini tidak diizinkan untuk peran Company Operator' }); + } + const session = await Session.findById(req.params.id).populate('user_id'); if (!session) { return res.status(404).json({ ok: false, error: 'Sesi tidak ditemukan' }); } - // Tenant Admin can only revoke sessions within their own site - if (req.adminUser.role !== 'SUPER_ADMIN') { - const sessionUser = session.user_id || {}; + const sessionUser = session.user_id || {}; + if (sessionUser.role === 'SUPER_ADMIN' && req.adminUser.role !== 'SUPER_ADMIN') { + return res.status(403).json({ ok: false, error: 'Forbidden' }); + } + + // Tenant / Company Admin can only revoke sessions within their own tenant/company + if (req.adminUser.role === 'COMPANY_ADMIN') { + if (sessionUser.company_name !== req.adminUser.company_name) { + return res.status(403).json({ ok: false, error: 'Unauthorized: Sesi berada di luar perusahaan Anda' }); + } + } else if (req.adminUser.role !== 'SUPER_ADMIN') { if (sessionUser.site_uuid !== req.adminUser.site_uuid) { return res.status(403).json({ ok: false, error: 'Unauthorized: Sesi berada di luar site Anda' }); } diff --git a/backend/routes/auth/settings.js b/backend/routes/auth/settings.js index 618efbb..cf98406 100644 --- a/backend/routes/auth/settings.js +++ b/backend/routes/auth/settings.js @@ -61,7 +61,7 @@ router.post('/change-username', requireAuth, async (req, res) => { user.username = newUsername; await user.save(); - const newToken = makeToken(user); + const newToken = makeToken(user, req.user.session_id); setCookieToken(res, newToken); res.json({ ok: true, message: 'Username berhasil diubah!', newUsername }); @@ -74,7 +74,7 @@ router.post('/change-username', requireAuth, async (req, res) => { router.post('/change-account-name', requireAuth, async (req, res) => { try { const { currentPassword, newAccountName } = req.body; - if (!currentPassword || newAccountName == null) { + if (!currentPassword || newAccountName == null || typeof currentPassword !== 'string' || typeof newAccountName !== 'string') { return res.status(400).json({ error: 'Current password and new account name are required' }); } if (!newAccountName.trim()) { @@ -91,7 +91,7 @@ router.post('/change-account-name', requireAuth, async (req, res) => { user.account_name = newAccountName.trim(); await user.save(); - const newToken = makeToken(user); + const newToken = makeToken(user, req.user.session_id); setCookieToken(res, newToken); res.json({ ok: true, message: 'Nama akun berhasil diubah!', newAccountName: user.account_name }); @@ -107,7 +107,7 @@ router.post('/upload-profile-picture', requireAuth, async (req, res) => { try { const { profile_picture_base64, user_id } = req.body; - if (!profile_picture_base64) { + if (!profile_picture_base64 || typeof profile_picture_base64 !== 'string') { return res.status(400).json({ error: 'No image data provided. Please select an image file first.' }); } @@ -128,28 +128,53 @@ router.post('/upload-profile-picture', requireAuth, async (req, res) => { // Tentukan target user (self atau admin update user lain) const targetId = user_id || req.user.id; + const isSelf = String(targetId) === String(req.user.id); + if (!isSelf) { + const allowedAdminRoles = ['SUPER_ADMIN', 'TENANT_ADMIN', 'COMPANY_ADMIN']; + if (!allowedAdminRoles.includes(req.user.role)) { + return res.status(403).json({ error: 'Forbidden: Cannot modify another user profile picture.' }); + } + } + const user = await User.findById(targetId); if (!user) return res.status(404).json({ error: 'User not found' }); + if (!isSelf) { + if (user.role === 'SUPER_ADMIN' && req.user.role !== 'SUPER_ADMIN') { + return res.status(403).json({ error: 'Forbidden' }); + } + if (req.user.role === 'COMPANY_ADMIN' && user.company_name !== req.user.company_name) { + return res.status(403).json({ error: 'Access Denied: User does not belong to your company.' }); + } + if (req.user.role === 'TENANT_ADMIN' && user.site_uuid !== req.user.site_uuid) { + return res.status(403).json({ error: 'Unauthorized: User does not belong to your tenant.' }); + } + } + + const uploadsDir = getUploadsDir(); + if (!fs.existsSync(uploadsDir)) { + fs.mkdirSync(uploadsDir, { recursive: true }); + } + // Hapus foto profil lama jika ada if (user.profile_picture) { - const oldPath = path.join(getUploadsDir(), user.profile_picture); + const oldPath = path.join(uploadsDir, path.basename(user.profile_picture)); if (fs.existsSync(oldPath)) { try { fs.unlinkSync(oldPath); } catch (_) {} } } // Simpan file baru - const filename = `profile-${targetId}-${Date.now()}.${ext}`; - const filePath = path.join(getUploadsDir(), filename); + const filename = `profile-${user._id.toString()}-${Date.now()}.${ext}`; + const filePath = path.join(uploadsDir, filename); fs.writeFileSync(filePath, base64Data, 'base64'); user.profile_picture = filename; await user.save(); // Perbarui token hanya jika user mengupdate foto dirinya sendiri - if (String(targetId) === String(req.user.id)) { - const newToken = makeToken(user); + if (isSelf) { + const newToken = makeToken(user, req.user.session_id); setCookieToken(res, newToken); } @@ -168,14 +193,14 @@ router.post('/remove-profile-picture', requireAuth, async (req, res) => { if (!user) return res.status(404).json({ error: 'User not found' }); if (user.profile_picture) { - const filePath = path.join(getUploadsDir(), user.profile_picture); + const filePath = path.join(getUploadsDir(), path.basename(user.profile_picture)); if (fs.existsSync(filePath)) fs.unlinkSync(filePath); } user.profile_picture = null; await user.save(); - const newToken = makeToken(user); + const newToken = makeToken(user, req.user.session_id); setCookieToken(res, newToken); res.json({ ok: true, message: 'Foto profil berhasil dihapus' }); diff --git a/backend/routes/auth/usersCreateExternal.js b/backend/routes/auth/usersCreateExternal.js index 40f0a0a..6d6adad 100644 --- a/backend/routes/auth/usersCreateExternal.js +++ b/backend/routes/auth/usersCreateExternal.js @@ -12,7 +12,7 @@ async function handleCreateExternalUser(req, res) { : (() => { try { return JSON.parse(req.body.agent_uuids); } catch { return [req.body.agent_uuids]; } })(); } - if (!username || !password || !role) { + if (!username || !password || !role || typeof username !== 'string' || typeof password !== 'string') { return res.status(400).json({ ok: false, error: 'Username, password, dan role wajib diisi' }); } @@ -21,8 +21,10 @@ async function handleCreateExternalUser(req, res) { validRoles = ['EXECUTIVE', 'SOC_ANALYST', 'ENGINEER', 'TENANT_ADMIN', 'COMPANY_ADMIN', 'COMPANY_OPERATOR', 'COMPANY_VIEWER']; } else if (req.adminUser.role === 'COMPANY_ADMIN') { validRoles = ['COMPANY_OPERATOR', 'COMPANY_VIEWER']; - } else { + } else if (req.adminUser.role === 'TENANT_ADMIN') { validRoles = ['SOC_ANALYST', 'ENGINEER', 'TENANT_ADMIN']; + } else { + return res.status(403).json({ ok: false, error: 'Forbidden' }); } if (!validRoles.includes(role)) { @@ -54,11 +56,11 @@ async function handleCreateExternalUser(req, res) { } const passwordHash = bcrypt.hashSync(password, 10); - const siteUuid = (role === 'EXECUTIVE' || role === 'COMPANY_ADMIN') + const siteUuid = (role === 'EXECUTIVE' || role === 'COMPANY_ADMIN' || role === 'COMPANY_OPERATOR' || role === 'COMPANY_VIEWER') ? null : req.adminUser.role === 'SUPER_ADMIN' ? (req.body.site_uuid || process.env.BACKONE_SITE_UUID || process.env.NETIFY_SITE_UUID) - : (req.body.site_uuid || null); + : req.adminUser.site_uuid; const createdBy = req.adminUser.role === 'SUPER_ADMIN' ? (req.body.created_by || req.adminUser.username) diff --git a/backend/routes/auth/viewAs.js b/backend/routes/auth/viewAs.js index 5017d27..1efa73c 100644 --- a/backend/routes/auth/viewAs.js +++ b/backend/routes/auth/viewAs.js @@ -23,13 +23,24 @@ router.post('/admin/view-as', requireAdmin, blockAnalyst, async (req, res) => { const ViewAsLog = mongoose.model('ViewAsLog'); const User = mongoose.model('User'); + if (['COMPANY_ADMIN', 'COMPANY_OPERATOR'].includes(req.adminUser.role)) { + const allowedAgents = req.adminUser.agent_uuids || []; + if (!allowedAgents.includes(agent_uuid)) { + return res.status(403).json({ ok: false, error: 'Akses ditolak: Anda tidak memiliki akses ke agent ini.' }); + } + } + let targetUserDoc = null; - if (target_user_id) { + if (target_user_id && typeof target_user_id === 'string') { targetUserDoc = await User.findById(target_user_id).lean(); - } else if (target_username) { + } else if (target_username && typeof target_username === 'string') { targetUserDoc = await User.findOne({ username: target_username }).lean(); } + if (targetUserDoc && targetUserDoc.role === 'SUPER_ADMIN' && req.adminUser.role !== 'SUPER_ADMIN') { + return res.status(403).json({ ok: false, error: 'Forbidden: Tidak dapat melihat sebagai SUPER_ADMIN.' }); + } + const payload = { adminId: req.adminUser.id, adminUsername: req.adminUser.username, diff --git a/backend/routes/dashboard/agents.js b/backend/routes/dashboard/agents.js index f683274..bbfedc4 100644 --- a/backend/routes/dashboard/agents.js +++ b/backend/routes/dashboard/agents.js @@ -191,6 +191,11 @@ router.get('/agents/list', async (req, res) => { return res.json({ ok: true, data: [] }); } filter.uuid = { $in: agentUuids }; + } else if (user?.role === 'AGENT_VIEWER' && !user?._originalRole) { + if (!user?.agent_uuid) { + return res.json({ ok: true, data: [] }); + } + filter.uuid = user.agent_uuid; } else { // Admin/SUPER_ADMIN: filter berdasarkan site UUID dari header const requestedSiteUuid = req.headers['x-backone-site-uuid']; @@ -234,8 +239,17 @@ router.get('/agents/list', async (req, res) => { // Kembalikan konfigurasi subnet yang diizinkan untuk agent tertentu router.get('/agents/:uuid/subnets', async (req, res) => { try { + const targetUuid = String(req.params.uuid || ''); + const companyRoles = ['COMPANY_ADMIN', 'COMPANY_OPERATOR', 'COMPANY_VIEWER']; + if (companyRoles.includes(req.user?.role)) { + if (!(req.user?.agent_uuids || []).includes(targetUuid)) { + return res.status(403).json({ ok: false, error: 'Forbidden' }); + } + } else if (req.user?.role === 'AGENT_VIEWER' && req.user?.agent_uuid !== targetUuid) { + return res.status(403).json({ ok: false, error: 'Forbidden' }); + } const db = mongoose.connection.db; - const doc = await db.collection('agent_registry').findOne({ uuid: req.params.uuid }); + const doc = await db.collection('agent_registry').findOne({ uuid: targetUuid }); res.json({ ok: true, data: { allowed_subnets: doc?.allowed_subnets || [] } }); } catch (err) { res.status(500).json({ ok: false, error: err.message }); @@ -272,10 +286,15 @@ router.put('/agents/:uuid/subnets', async (req, res) => { if (!allowedRoles.includes(req.user?.role)) { return res.status(403).json({ ok: false, error: 'Forbidden' }); } + const targetUuid = String(req.params.uuid || ''); + if (req.user?.role === 'COMPANY_ADMIN' && !(req.user?.agent_uuids || []).includes(targetUuid)) { + return res.status(403).json({ ok: false, error: 'Forbidden: Agent does not belong to your company.' }); + } const db = mongoose.connection.db; - const subnets = (req.body.allowed_subnets || []).map(s => s.trim()).filter(Boolean); + const subnets = (Array.isArray(req.body.allowed_subnets) ? req.body.allowed_subnets : []) + .map(s => String(s).trim()).filter(Boolean); await db.collection('agent_registry').updateOne( - { uuid: req.params.uuid }, + { uuid: targetUuid }, { $set: { allowed_subnets: subnets, subnets_updated_at: new Date() } } ); diff --git a/backend/routes/dashboard/apps.js b/backend/routes/dashboard/apps.js index 23033c8..c571374 100644 --- a/backend/routes/dashboard/apps.js +++ b/backend/routes/dashboard/apps.js @@ -149,10 +149,11 @@ router.get('/lookup/applications', async (req, res) => { let filter = {}; if (search) { + const safeSearch = search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); filter.$or = [ - { label: { $regex: search, $options: 'i' } }, - { name: { $regex: search, $options: 'i' } }, - { tag: { $regex: search, $options: 'i' } } + { label: { $regex: safeSearch, $options: 'i' } }, + { name: { $regex: safeSearch, $options: 'i' } }, + { tag: { $regex: safeSearch, $options: 'i' } } ]; } diff --git a/backend/routes/dashboard/devices.js b/backend/routes/dashboard/devices.js index 6c6f875..5e49c6a 100644 --- a/backend/routes/dashboard/devices.js +++ b/backend/routes/dashboard/devices.js @@ -152,15 +152,16 @@ router.get('/mac-bandwidth', async (req, res) => { // Returns IP history + bandwidth stats per MAC address (used by DeviceMacDetailsModal) router.get('/devices/mac-details', async (req, res) => { try { - const mac = (req.query.mac || '').toLowerCase().trim(); + const mac = String(req.query.mac || '').toLowerCase().trim(); if (!mac) return res.status(400).json({ ok: false, error: 'mac parameter required' }); + const safeMac = mac.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const timeFilter = getTimeFilter(req); const matchBase = getBaseFilter(req, timeFilter); // Aggregate IP history for this MAC: group by IP, sum bandwidth, track first/last seen const raw = await DeviceStat.aggregate([ - { $match: { ...matchBase, mac_address: { $regex: new RegExp(`^${mac.replace(/:/g, ':')}$`, 'i') } } }, + { $match: { ...matchBase, mac_address: { $regex: new RegExp(`^${safeMac}$`, 'i') } } }, { $group: { _id: '$ip_address', download: { $sum: '$download' }, diff --git a/backend/routes/dashboard/flows.js b/backend/routes/dashboard/flows.js index ed85538..109ef06 100644 --- a/backend/routes/dashboard/flows.js +++ b/backend/routes/dashboard/flows.js @@ -65,7 +65,7 @@ router.get('/flows', async (req, res) => { } if (req.query.search) { - const q = req.query.search.trim(); + const q = String(req.query.search).trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); if (q) { query.$or = [ { src_ip: { $regex: q, $options: 'i' } }, diff --git a/backend/routes/dashboard/helpers.js b/backend/routes/dashboard/helpers.js index ec294c8..c435b73 100644 --- a/backend/routes/dashboard/helpers.js +++ b/backend/routes/dashboard/helpers.js @@ -79,15 +79,18 @@ function getBaseFilter(req, timeFilter = null) { } else if (req.user?.role === 'AGENT_VIEWER' && req.user?.agent_uuid) { // AGENT_VIEWER is strictly limited to their own agent filter.agent_uuid = req.user.agent_uuid; - } else if (req.query?.agent_uuid) { + } else if (req.query?.agent_uuid && typeof req.query.agent_uuid === 'string') { // SUPER_ADMIN and other global roles can query any agent filter.agent_uuid = req.query.agent_uuid; } - console.log('[DEBUG getBaseFilter]', { headers: req.headers, filter }); return filter; } +function escapeRegex(str) { + return String(str || '').replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + async function getCustomLabelsMap() { try { const list = await CustomDeviceLabel.find().lean(); @@ -125,5 +128,6 @@ module.exports = { getBaseFilter, getCustomLabelsMap, topFlowField, - isKnownSite + isKnownSite, + escapeRegex }; diff --git a/backend/update_subnets.js b/backend/update_subnets.js deleted file mode 100644 index 556e1d7..0000000 --- a/backend/update_subnets.js +++ /dev/null @@ -1,24 +0,0 @@ -const mongoose = require('mongoose'); - -async function updateSubnets() { - await mongoose.connect('mongodb://backone_inspect:backone_inspect@mongodb.prod.proit.id:27017/backone_inspect_0'); - const db = mongoose.connection.db; - - await db.collection('agent_registry').updateOne( - { uuid: 'F6-2V-DT-8A' }, - { $set: { allowed_subnets: ['10.21', '192.168'] } } - ); - - await db.collection('agent_registry').updateOne( - { uuid: '8A-V3-PB-85' }, - { $set: { allowed_subnets: ['10.6'] } } - ); - - console.log('Subnets updated successfully.'); - process.exit(0); -} - -updateSubnets().catch(e => { - console.error(e); - process.exit(1); -}); diff --git a/check-logs.js b/check-logs.js deleted file mode 100644 index 7416be6..0000000 --- a/check-logs.js +++ /dev/null @@ -1 +0,0 @@ -const fetch = require(node-fetch); async function main() { console.log(Checking logs...); } main(); diff --git a/check-mongo.js b/check-mongo.js deleted file mode 100644 index 3a3cf7c..0000000 --- a/check-mongo.js +++ /dev/null @@ -1 +0,0 @@ -const mongoose = require(mongoose); mongoose.connect(mongodb://backone_inspect:backone_inspect@mongodb.prod.proit.id:27017/backone_inspect_0).then(async () => { console.log(SUMMARIES:, await mongoose.connection.collection(agent_summaries).countDocuments()); console.log(FLOWS:, await mongoose.connection.collection(flows).countDocuments()); process.exit(0); }); diff --git a/sftp-deploy-local.js b/sftp-deploy-local.js index ee82a63..88e75f2 100644 --- a/sftp-deploy-local.js +++ b/sftp-deploy-local.js @@ -7,10 +7,10 @@ const path = require('path'); const fs = require('fs'); const config = { - host: '103.185.47.52', - port: 2222, - username: 'adminbackend', - password: 'htEo7x6LsBQiEHHH', + host: process.env.SFTP_HOST || '103.185.47.52', + port: parseInt(process.env.SFTP_PORT || '2222', 10), + username: process.env.SFTP_USERNAME || 'adminbackend', + password: process.env.SFTP_PASSWORD || '', readyTimeout: 30000, retries: 2, retry_factor: 2, diff --git a/src/app/api/auth/admin/create-external-user/route.ts b/src/app/api/auth/admin/create-external-user/route.ts index b0e654c..a596d79 100644 --- a/src/app/api/auth/admin/create-external-user/route.ts +++ b/src/app/api/auth/admin/create-external-user/route.ts @@ -1,7 +1,6 @@ import { NextRequest, NextResponse } from "next/server"; import { cookies } from "next/headers"; - -const BACKEND_URL = process.env.NEXT_PUBLIC_API_URL || "http://127.0.0.1:3011"; +import { getApiBase } from "@/lib/api-base"; export async function POST(req: NextRequest) { try { @@ -22,7 +21,8 @@ export async function POST(req: NextRequest) { } }); - const destinationUrl = `${BACKEND_URL}/api/auth/admin/create-external-user`; + const backendUrl = await getApiBase(); + const destinationUrl = `${backendUrl}/api/auth/admin/create-external-user`; const response = await fetch(destinationUrl, { method: "POST", diff --git a/src/app/api/auth/admin/update-agent-user/route.ts b/src/app/api/auth/admin/update-agent-user/route.ts index fdb8602..6bb1d39 100644 --- a/src/app/api/auth/admin/update-agent-user/route.ts +++ b/src/app/api/auth/admin/update-agent-user/route.ts @@ -1,7 +1,6 @@ import { NextRequest, NextResponse } from "next/server"; import { cookies } from "next/headers"; - -const BACKEND_URL = process.env.NEXT_PUBLIC_API_URL || "http://127.0.0.1:3011"; +import { getApiBase } from "@/lib/api-base"; export async function POST(req: NextRequest) { try { @@ -22,7 +21,8 @@ export async function POST(req: NextRequest) { } }); - const destinationUrl = `${BACKEND_URL}/api/auth/admin/update-agent-user`; + const backendUrl = await getApiBase(); + const destinationUrl = `${backendUrl}/api/auth/admin/update-agent-user`; const response = await fetch(destinationUrl, { method: "POST", diff --git a/src/app/api/auth/remove-profile-picture/route.ts b/src/app/api/auth/remove-profile-picture/route.ts index ce2ab42..3fbadb3 100644 --- a/src/app/api/auth/remove-profile-picture/route.ts +++ b/src/app/api/auth/remove-profile-picture/route.ts @@ -3,8 +3,7 @@ import { NextRequest, NextResponse } from "next/server"; import { cookies } from "next/headers"; - -const BACKEND_URL = process.env.NEXT_PUBLIC_API_URL || "http://127.0.0.1:3001"; +import { getApiBase } from "@/lib/api-base"; export async function POST(req: NextRequest) { try { @@ -16,8 +15,9 @@ export async function POST(req: NextRequest) { headers["Cookie"] = `token=${token}`; } + const backendUrl = await getApiBase(); const backendRes = await fetch( - `${BACKEND_URL}/api/auth/remove-profile-picture`, + `${backendUrl}/api/auth/remove-profile-picture`, { method: "POST", headers, diff --git a/src/app/api/auth/upload-profile-picture/route.ts b/src/app/api/auth/upload-profile-picture/route.ts index 10ba2f3..f10ed61 100644 --- a/src/app/api/auth/upload-profile-picture/route.ts +++ b/src/app/api/auth/upload-profile-picture/route.ts @@ -1,7 +1,6 @@ import { NextRequest, NextResponse } from "next/server"; import { cookies } from "next/headers"; - -const BACKEND_URL = process.env.NEXT_PUBLIC_API_URL || "http://127.0.0.1:3011"; +import { getApiBase } from "@/lib/api-base"; export async function POST(req: NextRequest) { try { @@ -22,7 +21,8 @@ export async function POST(req: NextRequest) { } }); - const destinationUrl = `${BACKEND_URL}/api/auth/upload-profile-picture`; + const backendUrl = await getApiBase(); + const destinationUrl = `${backendUrl}/api/auth/upload-profile-picture`; const response = await fetch(destinationUrl, { method: "POST", @@ -32,12 +32,19 @@ export async function POST(req: NextRequest) { }); const responseBuffer = await response.arrayBuffer(); - return new NextResponse(responseBuffer, { + const nextResponse = new NextResponse(responseBuffer, { status: response.status, headers: { "Content-Type": response.headers.get("content-type") || "application/json", }, }); + + const setCookieHeader = response.headers.get("set-cookie"); + if (setCookieHeader) { + nextResponse.headers.set("Set-Cookie", setCookieHeader); + } + + return nextResponse; } catch (err: any) { console.error("[Upload Profile Picture Proxy] Error:", err.message); return NextResponse.json( diff --git a/src/app/api/dashboard/agents/list/route.ts b/src/app/api/dashboard/agents/list/route.ts index a5066a4..6bba94e 100644 --- a/src/app/api/dashboard/agents/list/route.ts +++ b/src/app/api/dashboard/agents/list/route.ts @@ -49,6 +49,11 @@ export async function GET(req: NextRequest) { return NextResponse.json({ ok: true, data: [] }); } filter.uuid = { $in: agentUuids }; + } else if (user?.role === 'AGENT_VIEWER' && !user?._originalRole) { + if (!user?.agent_uuid) { + return NextResponse.json({ ok: true, data: [] }); + } + filter.uuid = user.agent_uuid; } else { // Admin/SUPER_ADMIN: filter by site UUID const siteUuidHeader = req.headers.get('x-backone-site-uuid'); diff --git a/src/lib/actions/agents.ts b/src/lib/actions/agents.ts index c738ae6..2769492 100644 --- a/src/lib/actions/agents.ts +++ b/src/lib/actions/agents.ts @@ -15,6 +15,14 @@ import mongoose from "mongoose"; // Override mutations to use MongoDB for On-Premise mode export async function updateAgent(agentId: string, label: string) { try { + const user = await getAuthUser(); + if (!user || !['SUPER_ADMIN', 'TENANT_ADMIN'].includes(user.role)) { + return { success: false, message: "Unauthorized: Hanya Administrator yang dapat mengubah label agent." }; + } + if (!agentId || typeof agentId !== 'string' || typeof label !== 'string') { + return { success: false, message: "Parameter agentId dan label tidak valid." }; + } + const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/backone_dpi'; if (mongoose.connection.readyState !== 1) { await mongoose.connect(MONGODB_URI, { serverSelectionTimeoutMS: 5000 }); @@ -29,13 +37,18 @@ export async function updateAgent(agentId: string, label: string) { if (!agent) { return { success: false, message: "Agent tidak ditemukan di database lokal." }; } + + if (user.role === 'TENANT_ADMIN' && user.site_uuid && agent.site_uuid && agent.site_uuid !== user.site_uuid) { + return { success: false, message: "Forbidden: Agent bukan milik tenant Anda." }; + } // Write both label AND protected_label. // protected_label is ONLY set by the UI — the Proxy NEVER touches it. // This ensures custom names survive even if the Proxy overwrites label field. + const cleanLabel = label.trim(); await db.collection('agent_registry').updateOne( { _id: agent._id }, - { $set: { label: label, protected_label: label } } + { $set: { label: cleanLabel, protected_label: cleanLabel } } ); // Bismillah: Hapus semua data duplikat/hantu milik agent ini agar tidak ditimpa oleh proxy lawas/bug ganda @@ -47,7 +60,7 @@ export async function updateAgent(agentId: string, label: string) { // Also try to update the summaries if possible, so historical displays match await db.collection('summaries').updateMany( { agent_uuid: agent.uuid }, - { $set: { agent_label: label } } + { $set: { agent_label: cleanLabel } } ); const { revalidatePath } = require('next/cache'); @@ -61,6 +74,14 @@ export async function updateAgent(agentId: string, label: string) { export async function deleteAgent(agentId: string) { try { + const user = await getAuthUser(); + if (!user || !['SUPER_ADMIN', 'TENANT_ADMIN'].includes(user.role)) { + return { success: false, message: "Unauthorized: Hanya Administrator yang dapat menghapus agent." }; + } + if (!agentId || typeof agentId !== 'string') { + return { success: false, message: "Parameter agentId tidak valid." }; + } + const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/backone_dpi'; if (mongoose.connection.readyState !== 1) { await mongoose.connect(MONGODB_URI, { serverSelectionTimeoutMS: 5000 }); @@ -75,6 +96,10 @@ export async function deleteAgent(agentId: string) { if (!agent) { return { success: false, message: "Agent tidak ditemukan di database lokal." }; } + + if (user.role === 'TENANT_ADMIN' && user.site_uuid && agent.site_uuid && agent.site_uuid !== user.site_uuid) { + return { success: false, message: "Forbidden: Agent bukan milik tenant Anda." }; + } await db.collection('agent_registry').deleteOne({ _id: agent._id }); diff --git a/src/lib/actions/agentsCore.ts b/src/lib/actions/agentsCore.ts index 1858a9d..b550352 100644 --- a/src/lib/actions/agentsCore.ts +++ b/src/lib/actions/agentsCore.ts @@ -1,4 +1,5 @@ import { revalidatePath } from "next/cache"; +import { getAuthUser } from "./authHelper"; export const BASE_URL = process.env.BACKONE_BASE_URL || process.env.NETIFY_BASE_URL || process.env.BACKONE_INFORMATICS_BASE_URL || process.env.NETIFY_INFORMATICS_BASE_URL || "http://127.0.0.1:3011"; export const API_URL = `${BASE_URL}/assets/agents`; @@ -49,6 +50,11 @@ export const getHeaders = () => { export async function createAgent(agentId: string, label: string) { try { + const user = await getAuthUser(); + if (!user || !['SUPER_ADMIN', 'TENANT_ADMIN'].includes(user.role)) { + return { success: false, message: "Unauthorized: Hanya Administrator yang dapat membuat Agents." }; + } + const API_KEY = getApiKey(); if (API_KEY && API_KEY.startsWith("sk_db_")) { return { success: false, message: "Aksi ditolak: Site-scoped API Key tidak diperbolehkan membuat Agents." };