#!/usr/bin/env node // NYX PROJECT — terminal toolkit · modul bima (Tri/IOH) // Author: Akwila Dimas · https://github.com/Akwds01 // Telegram: https://t.me/nyx_projectss · WhatsApp: https://whatsapp.com/channel/0029VbEMMAQHbFUzKKOE5o0Y // Sumber: vermaysha/bima-plus · 0xtbug/telbot · Najihh/EnQuota · gist myIM3 (ayashiiiyo) // License: MIT (2026, Akwila Dimas) — bebas dipakai/diubah/dibagikan dengan notice // File tunggal hasil build dari cli.mjs + lib/{bima,ui,brand}.mjs import readline from 'node:readline/promises'; // NYX PROJECT — terminal toolkit (modul: bima / Tri-IOH) // Author : Akwila Dimas // GitHub : https://github.com/Akwds01 // Telegram: https://t.me/nyx_projectss · https://t.me/NYX_PROJECTS // WhatsApp: https://whatsapp.com/channel/0029VbEMMAQHbFUzKKOE5o0Y // Sumber / referensi: // - https://github.com/vermaysha/bima-plus // - https://github.com/0xtbug/telbot // - https://github.com/Najihh/EnQuota // - https://gist.github.com/ayashiiiyo/e2561dddd66e1259a17b3eac28c47b55 (myIM3) // Detail di CLI: `nyx about` · link: `nyx links` // License : MIT (2026, Akwila Dimas) // Bima+ (Tri / IOH) API client — Node 18+, tanpa dependency. // Bagian dari bima-cli. Semua endpoint & resep terdokumentasi di README.md / FINDINGS.md. import crypto from 'node:crypto'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; /* ------------------------------------------------------------------ config */ export const BASE_URL = process.env.BIMA_BASE_URL || 'https://bimaplus-api.ioh.co.id/api/v2'; export const APP_VERSION = process.env.BIMA_APP_VERSION || '5.18.0'; export const CHANNEL = process.env.BIMA_CHANNEL || 'BIMA'; // app = BIMA, web = PORTAL const OS = process.env.BIMA_OS || 'Android'; const LANGUAGE = 'ID'; const SERVICE_KEY = 'FPi7ZP3Jy8Uv3KBd4QeG'; const HDR_AUTHORIZATION = '642d1cc69d90666962726e'; const AES_KEY = 'A9$gT#2vXp!qW7LmZ@e4Ky8Nb3Hj5Uq9'; const AES_IV = 'Rx4Cm9Pn2Vf8Kt6B'; const TIMEOUT_MS = Number(process.env.BIMA_TIMEOUT_MS || 30000); // Penyimpanan: ~/.nyx (brand baru), dengan fallback ke ~/.bima untuk instalasi lama. const NYX_DIR = path.join(os.homedir(), '.nyx'); const LEGACY_DIR = path.join(os.homedir(), '.bima'); const pilihSession = () => { if (process.env.BIMA_SESSION) return process.env.BIMA_SESSION; for (const f of [path.join(NYX_DIR, 'session.json'), path.join(LEGACY_DIR, 'session.json')]) { try { if (fs.existsSync(f)) return f; } catch {} } return path.join(NYX_DIR, 'session.json'); }; export const SESSION_PATH = pilihSession(); export const categoryCachePath = (msisdn) => path.join(path.dirname(SESSION_PATH), `categories${msisdn ? '-' + String(msisdn) : ''}.json`); const DEVICE_ID_PATH = path.join(path.dirname(SESSION_PATH), 'device.id'); /** Device ID acak per instalasi (bukan kredensial; bisa di-set via BIMA_DEVICE_ID). */ const resolveDeviceId = () => { if (process.env.BIMA_DEVICE_ID) return process.env.BIMA_DEVICE_ID; try { const t = fs.readFileSync(DEVICE_ID_PATH, 'utf8').trim(); if (/^[0-9a-f]{32}$/i.test(t)) return t; } catch {} const id = crypto.randomBytes(16).toString('hex'); try { fs.mkdirSync(path.dirname(DEVICE_ID_PATH), { recursive: true }); fs.writeFileSync(DEVICE_ID_PATH, id, { mode: 0o600 }); } catch {} return id; }; export const ENDPOINTS = Object.freeze({ guest: '/token/guest/v1', sendOtp: '/otp/send/v1', validateOtp: '/otp/validate/v2', profile: '/profile/get', dashboard: '/dashboard/get/v4', customerProfile: '/customerprofile/get', subscriberType: '/subscriber/gettype/v1', categories: '/appinit/all/categories', packageList: '/packages/getpackagelist?catid=', categoryTree: '/appinit/all/categories', packageDetail: '/packages/getpackage', personalize: '/personalization/packs', cvmOffers: '/dmp/personalization/cvmoffers', paymentChannels: '/payment/checkavailability', paymentDenoms: '/payment/getdenoms/v1', initiatePayment: '/esb/initiatepayment/v5', transactionHistory: '/transaction/history', transactionDetail: '/transaction/getbyid/v1', emgList: '/emg/servicelist/v1', emgActivate: '/emg/activate/v1', pointStatus: '/lms/bonstri/pointstatus', rewards: '/lms/bonstri/rewards', vouchers: '/lms/myvouchers', redeem: '/lms/redeem', notifications: '/notifications/list/v2', lines: '/primary/lines', }); /* ------------------------------------------------------------------ crypto */ export const sha512 = (s) => crypto.createHash('sha512').update(String(s), 'utf8').digest('hex'); /** Ambil karakter pada indeks genap: 'abcdef' -> 'ace' */ export const oddChars = (s) => [...String(s)].filter((_, i) => i % 2 === 0).join(''); /** AES-256-GCM, IV 16 byte, Base64 tanpa wrap — sama dengan ODPAESEncryption.encryptNew() */ export const encryptGcm = (plain) => { const c = crypto.createCipheriv('aes-256-gcm', Buffer.from(AES_KEY, 'utf8'), Buffer.from(AES_IV, 'utf8')); return Buffer.concat([c.update(String(plain), 'utf8'), c.final(), c.getAuthTag()]).toString('base64'); }; export const decryptGcm = (b64) => { const raw = Buffer.from(String(b64), 'base64'); const d = crypto.createDecipheriv('aes-256-gcm', Buffer.from(AES_KEY, 'utf8'), Buffer.from(AES_IV, 'utf8')); d.setAuthTag(raw.subarray(raw.length - 16)); return Buffer.concat([d.update(raw.subarray(0, raw.length - 16)), d.final()]).toString('utf8'); }; export const rc4Hex = (value, password = '123') => { const bytes = Buffer.from(String(value), 'utf8'); const sbox = [...Array(256).keys()]; const key = [...password].map((c) => c.charCodeAt(0)); let j = 0; for (let i = 0; i < 256; i += 1) { j = (j + sbox[i] + key[i % key.length]) % 256; [sbox[i], sbox[j]] = [sbox[j], sbox[i]]; } let a = 0; let b = 0; const out = Buffer.alloc(bytes.length); for (let n = 0; n < bytes.length; n += 1) { a = (a + 1) % 256; b = (b + sbox[a]) % 256; [sbox[a], sbox[b]] = [sbox[b], sbox[a]]; out[n] = bytes[n] ^ sbox[(sbox[a] + sbox[b]) % 256]; } return out.toString('hex'); }; /* -------------------------------------------------------------- formatting */ export const msisdn62 = (v) => { const d = String(v ?? '').replace(/\D/g, ''); if (d.startsWith('62')) return d; if (d.startsWith('0')) return `62${d.slice(1)}`; return `62${d}`; }; export const localMsisdn = (v) => { const d = msisdn62(v); return `0${d.slice(2)}`; }; export const rupiah = (n) => 'Rp' + Number(n || 0).toLocaleString('id-ID'); export const qrisImageUrl = (payload, size = 700) => `https://api.qrserver.com/v1/create-qr-code/?size=${size}x${size}&margin=10&data=${encodeURIComponent(payload)}`; /** Validasi CRC-16/CCITT-FALSE payload EMVCo QRIS */ export const qrisCrcOk = (payload) => { if (!payload || payload.length < 8) return false; const body = payload.slice(0, -4); const given = payload.slice(-4).toUpperCase(); let crc = 0xffff; for (let i = 0; i < body.length; i += 1) { crc ^= body.charCodeAt(i) << 8; for (let k = 0; k < 8; k += 1) crc = crc & 0x8000 ? ((crc << 1) ^ 0x1021) & 0xffff : (crc << 1) & 0xffff; } return given === crc.toString(16).toUpperCase().padStart(4, '0'); }; /* ------------------------------------------------------------------ errors */ export class BimaError extends Error { constructor(message, { code = 'BIMA_ERROR', status = null, details = null } = {}) { super(message); this.name = 'BimaError'; this.code = String(code); this.status = status; this.details = details; } } const stamp = (d = new Date()) => { const p = (n, l = 2) => String(n).padStart(l, '0'); return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}${p(d.getMilliseconds(), 3)}`; }; /* ----------------------------------------------------------------- session */ export const loadSession = (file = SESSION_PATH) => { try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; } }; export const saveSession = (session, file = SESSION_PATH) => { fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); fs.writeFileSync(file, JSON.stringify(session, null, 2), { mode: 0o600 }); return file; }; /* ------------------------------------------------------------------ client */ export class BimaClient { constructor({ msisdn = null, tokenId = null, deviceId = resolveDeviceId(), cookies = '' } = {}) { this.msisdn = msisdn ? msisdn62(msisdn) : null; this.tokenId = tokenId; this.deviceId = deviceId || resolveDeviceId(); this.cookies = cookies; this.pendingTransId = null; // transid sesi OTP this.raw = {}; } static fromSession(session) { if (!session?.tokenId) throw new BimaError('Sesi tidak ditemukan — jalankan `login` dulu.', { code: 'NO_SESSION' }); return new BimaClient(session); } session() { return { msisdn: this.msisdn, tokenId: this.tokenId, deviceId: this.deviceId, cookies: this.cookies, savedAt: new Date().toISOString() }; } headers(bodyStr, { channel = CHANNEL, os = OS, version = APP_VERSION } = {}) { const tokenId = this.tokenId || stamp() + '1'; const uid = stamp() + String(Math.floor(100 + Math.random() * 900)); const h = { authorization: HDR_AUTHORIZATION, 'x-imi-servicekey': SERVICE_KEY, 'x-imi-channel': channel, 'x-imi-language': LANGUAGE, 'x-imi-app-os': os, 'x-imi-appversion': version, 'x-imi-version': version, 'x-imi-tokenid': tokenId, 'x-imi-uid': uid, 'x-imi-oauth': sha512(`REQBODY=${bodyStr}&SALT=${oddChars(tokenId)}`), 'x-imi-hash': sha512(`parent$${os}$${version}$${tokenId}&SALT=${oddChars(uid)}`), 'x-deviceid': this.deviceId, 'x-devicename': process.env.BIMA_DEVICE_NAME || 'bima-cli', 'content-type': 'application/json; charset=utf-8', accept: 'application/json', 'user-agent': process.env.BIMA_UA || 'okhttp/4.12.0', }; if (this.cookies) h.cookie = this.cookies; return h; } /** Bangun perintah curl setara untuk request ini (untuk dibagikan/di-debug). */ buildCurl(endpoint, body = {}, opts = {}) { const bodyStr = typeof body === 'string' ? body : JSON.stringify(body); const h = this.headers(bodyStr, opts); const parts = [`curl -sS -X POST '${BASE_URL}${endpoint}'`]; for (const [k, v] of Object.entries(h)) { if (k === 'cookie') continue; parts.push(` -H '${k}: ${String(v).replace(/'/g, "'\\''")}'`); } parts.push(` --data-raw '${bodyStr.replace(/'/g, "'\\''")}'`); return parts.join(' \\\n'); } absorbCookies(res) { const set = res.headers.getSetCookie ? res.headers.getSetCookie() : []; if (!set.length) return; const jar = {}; for (const c of String(this.cookies || '').split(';')) { const [k, ...v] = c.trim().split('='); if (k) jar[k] = v.join('='); } for (const c of set) { const main = c.split(';')[0].trim(); const [k, ...v] = main.split('='); if (k) jar[k] = v.join('='); } this.cookies = Object.entries(jar).map(([k, v]) => `${k}=${v}`).join('; '); } /** POST mentah. `body` boleh objek (dijsonkan) atau string (mis. body terenkripsi). */ async post(endpoint, body = {}, opts = {}) { const bodyStr = typeof body === 'string' ? body : JSON.stringify(body); const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), TIMEOUT_MS); let res; try { res = await fetch(BASE_URL + endpoint, { method: 'POST', headers: this.headers(bodyStr, opts), body: bodyStr, signal: controller.signal, }); } catch (err) { throw new BimaError(`Gagal konek ke server: ${err.message}`, { code: 'NETWORK' }); } finally { clearTimeout(timer); } this.absorbCookies(res); const text = await res.text(); let json = null; try { json = JSON.parse(text); } catch { /* bukan JSON */ } if (!json) throw new BimaError(`Respons bukan JSON (HTTP ${res.status})`, { code: 'NOT_JSON', status: res.status, details: text.slice(0, 300) }); if (json.status !== '0' && json.status !== 0) { const err = new BimaError(json.message || json.returnmsg || `Gagal memanggil ${endpoint}`, { code: json.code ?? 'API_ERROR', status: res.status, details: json, }); err.body = json; throw err; } return json; } /* -------------------------------------------------------------- auth */ async guest() { const j = await this.post(ENDPOINTS.guest, {}); this.tokenId = j.data?.tokenid ?? j.data?.token ?? null; return this.tokenId; } async requestOtp(msisdn = this.msisdn) { this.msisdn = msisdn62(msisdn); if (!this.tokenId) await this.guest(); const j = await this.post(ENDPOINTS.sendOtp, { msisdn: this.msisdn, action: 'register' }); this.pendingTransId = j.transid ?? j.data?.transid ?? null; return { transid: this.pendingTransId, raw: j }; } async submitOtp(otp, transid = this.pendingTransId) { const j = await this.post(ENDPOINTS.validateOtp, { transid: transid || '', otp: String(otp).trim() }); const token = j.data?.tokenid ?? j.data?.token; if (!token) throw new BimaError('OTP ditolak server.', { code: 'OTP_REJECTED', details: j }); this.tokenId = token; return { token, raw: j }; } /* -------------------------------------------------------------- read */ dashboard() { return this.post(ENDPOINTS.dashboard, {}); } profile() { return this.post(ENDPOINTS.profile, {}); } categories() { return this.post(ENDPOINTS.categories, {}); } points() { return this.post(ENDPOINTS.pointStatus, {}); } rewards() { return this.post(ENDPOINTS.rewards, {}); } vouchers() { return this.post(ENDPOINTS.vouchers, {}); } notifications() { return this.post(ENDPOINTS.notifications, {}); } lines() { return this.post(ENDPOINTS.lines, {}); } history() { return this.post(ENDPOINTS.transactionHistory, {}); } packageList(catid = '31') { return this.post(ENDPOINTS.packageList + catid, { msisdn: this.msisdn ?? '' }); } /** Daftar subkategori dari CMS. Menggabungkan semua bahasa (id/en) & dedupe per id. */ async categoryTree() { const j = await this.post(ENDPOINTS.categoryTree, {}); const d = j.data ?? {}; const langs = Object.keys(d).filter((k) => d[k] && typeof d[k] === 'object'); const rows = []; const seen = new Set(); for (const lang of langs) { for (const arr of Object.values(d[lang])) { for (const cat of arr ?? []) { const parent = String(cat.title ?? '').trim(); const parentId = String(cat.categoryid ?? ''); for (const sub of cat.categories ?? []) { const id = String(sub.categoryid ?? ''); if (!id || id === 'null' || seen.has(id)) continue; seen.add(id); rows.push({ id, title: String(sub.title ?? '').replace(/\s+/g, ' ').trim(), parent, parentId, lang }); } } } } return rows; } /** Jumlah paket per subkategori (cached 24 jam per nomor di ~/.bima/categories-.json). */ async categoryCounts({ force = false } = {}) { const tree = await this.categoryTree(); const cachePath = categoryCachePath(this.msisdn); let cache = null; if (!force) { try { const raw = JSON.parse(fs.readFileSync(cachePath, 'utf8')); if (Date.now() - (raw.ts ?? 0) < 24 * 3600 * 1000) cache = raw.counts; } catch {} } if (cache) return tree.map((t) => ({ ...t, count: cache[t.id] ?? 0 })); const guest = new BimaClient({ msisdn: this.msisdn }); try { await guest.guest(); } catch {} const counts = {}; const queue = [...tree]; const worker = async () => { while (queue.length) { const t = queue.shift(); let n = 0; const own = await this.packages(t.id); n = own.length; if (!n) { try { n = (await guest.packages(t.id)).length; } catch {} } counts[t.id] = n; } }; await Promise.all(Array.from({ length: 8 }, worker)); try { fs.mkdirSync(path.dirname(cachePath), { recursive: true }); fs.writeFileSync(cachePath, JSON.stringify({ ts: Date.now(), counts }), { mode: 0o600 }); } catch {} return tree.map((t) => ({ ...t, count: counts[t.id] ?? 0 })); } /** Penawaran personal + CVM (diskon khusus nomor ini). */ async promotions() { const out = []; for (const [ep, jenis] of [[ENDPOINTS.personalize, 'personal'], [ENDPOINTS.cvmOffers, 'cvm']]) { try { const j = await this.post(ep, { msisdn: this.msisdn ?? '' }); for (const p of (j.data?.commercial_package ?? [])) { out.push(catalogOf({ data: { commercial_package: [p] } })[0] && { ...catalogOf({ data: { commercial_package: [p] } })[0], jenis }); } } catch {} } const seen = new Set(); return out.filter(Boolean) .filter((p) => p.pvrCode && !seen.has(p.pvrCode) && seen.add(p.pvrCode)) .sort((a, b) => a.price - b.price); } /** Paket dalam satu (sub)kategori; kategori tanpa hasil → array kosong, bukan error. */ async packages(catid) { try { const j = await this.post(ENDPOINTS.packageList + catid, { msisdn: this.msisdn ?? '' }); return Array.isArray(j?.data?.commercial_package) ? j.data.commercial_package : []; } catch { return []; } } detail(pvrCode, cvmtype = 0) { return this.post(ENDPOINTS.packageDetail, { servicename: 'GET PACKAGE', PVR_CODE: String(pvrCode), cvmtype }); } channels(paymentMethods = 'BALANCE,QRIS,DANA,SHOPEEPAY,GOPAY,OVO', extra = {}) { return this.post(ENDPOINTS.paymentChannels, { paymentchannels: paymentMethods, transtype: 'package', operationtype: 'buy', ...extra }); } emgList() { return this.post(ENDPOINTS.emgList, {}); } /* -------------------------------------------------------------- beli */ /** * Buat tagihan QRIS. Mengembalikan { transid, amount, expiryMinutes, payload, nmid, imageUrl }. * Body WAJIB terenkripsi + wajib ada due/duedate/balancereceive/quota/packvalidity. */ /** Body QRIS (objek polos, sebelum enkripsi) — dipakai buyQris & buildCurl. */ qrisBodyPlain({ pvrCode, keyword, packageName, price, validity = '1', toMSISDN = this.msisdn, channel = 'QRIS' }) { return { discountprice: String(price), keyword: keyword ?? '', name: '', normalprice: String(price), offerid: String(pvrCode), operationtype: 'buy', packagename: packageName, paymentchannel: channel, shortcode: '', tomsisdn: msisdn62(toMSISDN), transid: '', transtype: 'package', walletmsisdn: '', validity: String(validity), due: Number(price), duedate: '', balancereceive: 0, quota: '', packvalidity: String(validity), }; } /** Body QRIS siap kirim (string terenkripsi) — dipakai `--curl`. */ qrisBody(opts) { return encryptGcm(JSON.stringify(this.qrisBodyPlain(opts))); } async buyQris(opts) { const body = this.qrisBodyPlain(opts); const j = await this.post(ENDPOINTS.initiatePayment, encryptGcm(JSON.stringify(body))); const d = j.data?.SendPaymentResp ?? j.data; if (!d?.actionData) throw new BimaError('Server tidak mengembalikan payload QRIS.', { code: 'NO_QRIS', details: j }); return { transid: d.uniqueTransactionCode ?? j.transid, amount: d.amount, expiryMinutes: d.expiryTime, payload: d.actionData, nmid: d.nmid, crcValid: qrisCrcOk(d.actionData), imageUrl: qrisImageUrl(d.actionData), raw: d, }; } async activateEmergency({ actioncode, name, price, amount, fee, period, periodUnit, toMSISDN = this.msisdn, currency = 'IDR' }) { const body = { keyword: actioncode, shortcode: 'SOS', operationtype: 'ADDED', offerid: actioncode, tomsisdn: msisdn62(toMSISDN), packagename: name, name: '', normalprice: String(amount), discountprice: String(fee), due: Number(price), balancereceive: Number(amount), validity: `${period}/${periodUnit}`, emgtype: 0, currencycode: currency, }; return this.post(ENDPOINTS.emgActivate, encryptGcm(JSON.stringify(body))); } /* -------------------------------------------------------------- util */ async pendingQrisOrders() { const j = await this.history(); return (j.data?.transactions ?? []) .filter((t) => /pending/i.test(String(t.status)) && /qris/i.test(String(t.paymentmethod))) .map((t) => ({ transid: t.tid, product: t.productname, amount: Number(t.price), createdAt: t.datetime, expiryMinutes: Number(t.expirytime || 0), payload: t.aj_reference_id, crcValid: qrisCrcOk(t.aj_reference_id || ''), imageUrl: qrisImageUrl(t.aj_reference_id || ''), })); } } /* ------------------------------------------------------------- normalizers */ export const balanceOf = (dashboardData) => { const b = dashboardData?.prepaidinfo?.balance ?? dashboardData?.packdata?.lastbalance ?? null; return b == null ? null : Number(b); }; export const activePackagesOf = (dashboardData) => (dashboardData?.packdata?.packageslist ?? []).map((p) => ({ name: p.PackageName ?? p.ServiceName ?? '(tanpa nama)', expires: p.EndDate ?? p.expMsg ?? null, status: p.packagestatus ?? null, })); export const quotasOf = (dashboardData) => { const out = []; for (const pkg of dashboardData?.packdata?.packageslist ?? []) { for (const q of pkg.Quotas ?? []) { const rem = q.remainingQuota != null ? Number(q.remainingQuota) : Number(q.rawRemainingQuota ?? 0); const unit = String(q.quotaUnit || '').toUpperCase(); const text = unit === 'MB' && rem >= 1024 ? `${(rem / 1024).toFixed(2)} GB` : `${rem} ${q.quotaUnit ?? ''}`.trim(); out.push({ package: pkg.PackageName ?? pkg.ServiceName, name: q.name ?? q.description ?? '-', type: q.benefitType ?? '', remaining: text, remainingRaw: rem, until: pkg.EndDate ?? pkg.expMsg ?? null }); } } return out; }; /** Ringkasan kuota dari dashboard.summary. */ export const summaryOf = (data) => { const s = data?.summary?.data ?? {}; const kb = Number(s.initialquota ?? 0); return { used: Number(s.usedquota ?? 0), remaining: Number(s.remainingquota ?? 0), initial: kb, unit: s.quotaunit ?? 'KB', unlimited: Boolean(s.isunlimited), }; }; /** Format byte → GB/MB ringkas. */ export const fmtBytes = (b) => { const n = Number(b ?? 0); if (!n) return '0 B'; if (n >= 1073741824) return (n / 1073741824).toFixed(2).replace(/\.00$/, '') + ' GB'; if (n >= 1048576) return Math.round(n / 1048576) + ' MB'; if (n >= 1024) return Math.round(n / 1024) + ' KB'; return Math.round(n) + ' B'; }; /** Format KB (dipakai summary dashboard) → GB/MB. */ export const fmtKB = (kb) => fmtBytes(Number(kb ?? 0) * 1024); /** Daftar paket aktif lengkap dengan kuota per item. */ export const activePackageDetails = (data) => { const list = data?.packdata?.packageslist ?? []; return list.map((p) => ({ name: p.PackageName ?? p.ServiceDescription ?? '-', type: p.ServiceType ?? '', code: String(p.PackageCode ?? '').split(':')[0], start: p.StartDate ?? '', end: p.EndDate ?? '', quotas: (p.Quotas ?? []).filter((q) => q.show !== 'OFF').map((q) => { const f = q.quotaUnit === 'GB' ? 1073741824 : q.quotaUnit === 'MB' ? 1048576 : q.quotaUnit === 'KB' ? 1024 : 1; const rem = Number(q.rawRemainingQuota ?? 0) || Number(q.remainingQuota ?? 0) * f; const ini = Number(q.rawInitialQuota ?? 0) || Number(q.initialQuota ?? 0) * f; return { name: q.name ?? q.description ?? '-', remaining: Math.max(0, rem), initial: Math.max(0, ini), used: Math.max(0, Number(q.rawUsedQuota ?? 0) || 0), unit: q.quotaUnit ?? 'KB', monetary: q.quotaUnit === 'MONETARY', expiry: q.expiryDate ? String(q.expiryDate).replace(/(\d{4})(\d{2})(\d{2})/, '$3.$2.$1') : '', benefit: q.benefitType ?? '', }; }), })); }; export const catalogOf = (data) => { const raw = data?.data ?? data; const list = raw?.commercial_package ?? raw?.packageslist ?? raw?.packages ?? []; return (Array.isArray(list) ? list : []).map((p) => ({ pvrCode: String(p.pvr_code ?? p.offerid ?? p.product_id ?? p.id ?? ''), name: p.package_name ?? p.name ?? p.title ?? '', price: Number(p.tariff ?? p.price ?? 0), originalPrice: Number(p.original_tariff ?? p.tariff ?? p.price ?? 0), validity: p.commercial_attribute?.duration_month || (String(p.package_name ?? '').match(/\d+\s*(hari|hr|day|days|bulan|month)/i)?.[0] ?? p.validity ?? null), family: p.commercial_attribute?.family_name ?? '', keyword: p.keyword ?? '', shortcode: p.shortcode ?? '', channels: p.paymentchannels ?? p.commercial_attribute?.payment_methods ?? '', ribbon: p.package_ribbon ?? '', })); }; export const channelsOf = (data) => (data?.sofAvailability ?? []).map((c) => ({ id: c.channelid, name: c.name, gateway: c.paymentgw, group: c.groupname })); export const rewardsOf = (data) => (data?.products?.product ?? []).map((p) => ({ id: p.productid, name: p.productname, points: Number(p.productpoints ?? 0), category: p.category ?? p.productcategory ?? '', stock: p.stock, partner: p.partnername ?? '', })); export default { BimaClient, BimaError, ENDPOINTS, loadSession, saveSession, SESSION_PATH, encryptGcm, decryptGcm, rc4Hex, sha512, oddChars, qrisImageUrl, qrisCrcOk, msisdn62, localMsisdn, rupiah, balanceOf, activePackagesOf, quotasOf, catalogOf, channelsOf, rewardsOf, }; /* ========================== BRAND =========================== */ // Identitas & kredit NYX PROJECT. Isi link di sini — otomatis muncul di // `nyx about`, banner, dan README. Bisa juga lewat env: NYX_AUTHOR, NYX_GITHUB, // NYX_WA, NYX_TG, NYX_TG_PERSONAL. const BRAND = { name: 'NYX PROJECT', tagline: 'terminal toolkit', version: '1.0.0', author: process.env.NYX_AUTHOR || 'Akwila Dimas', github: process.env.NYX_GITHUB || 'https://github.com/Akwds01', waChannel: process.env.NYX_WA || 'https://whatsapp.com/channel/0029VbEMMAQHbFUzKKOE5o0Y', telegram: process.env.NYX_TG || 'https://t.me/nyx_projectss', // channel NYX telegramPersonal: process.env.NYX_TG_PERSONAL || 'https://t.me/NYX_PROJECTS', // kontak/akun refs: [ ['vermaysha/bima-plus', 'https://github.com/vermaysha/bima-plus'], ['0xtbug/telbot', 'https://github.com/0xtbug/telbot'], ['Najihh/EnQuota', 'https://github.com/Najihh/EnQuota'], ['gist myIM3 (ayashiiiyo)', 'https://gist.github.com/ayashiiiyo/e2561dddd66e1259a17b3eac28c47b55'], ], }; /** Baris kredit ringkas untuk banner/help. */ const creditLine = () => { const bits = [`by ${BRAND.author}`]; if (BRAND.github) bits.push(BRAND.github.replace(/^https?:\/\//, '')); if (BRAND.telegram) bits.push('t.me/nyx_projectss'); return bits.join(' · '); }; /* =========================== TSEL =========================== */ // NYX PROJECT — modul tsel (Telkomsel / MyTelkomsel), Node ESM, tanpa dependency. // Alur: CIAM OTP (ciam.telkomsel.com) -> OAuth code -> access_token, lalu API tdw. // Author: Akwila Dimas · MIT · referensi: web app my.telkomsel.com // Alur: CIAM OTP login (ciam.telkomsel.com) -> OAuth code -> access_token, // lalu panggil API tdw.telkomsel.com dengan header terenkripsi AES-128-OFB. const CIAM = 'https://ciam.telkomsel.com'; const REALM = 'tsel'; const CLIENT_ID = 'e7126474617aa39eb9e484233c9b0649'; const CLIENT_SECRET = 'P@ssw0rd'; const REDIRECT_URI = 'https://my.telkomsel.com/web/callback'; const API = 'https://tdw.telkomsel.com'; const WEB_VERSION = '2.0.0'; const ENC_PASSWORD = 'production'; const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36'; const TSEL_SESSION_PATH = process.env.NYX_TSEL_SESSION || path.join(os.homedir(), '.nyx', 'tsel-session.json'); const loadTselSession = () => { try { return JSON.parse(fs.readFileSync(TSEL_SESSION_PATH, 'utf8')); } catch { return null; } }; const saveTselSession = (s) => { fs.mkdirSync(path.dirname(TSEL_SESSION_PATH), { recursive: true }); fs.writeFileSync(TSEL_SESSION_PATH, JSON.stringify({ ...s, savedAt: new Date().toISOString() }, null, 2), { mode: 0o600 }); return TSEL_SESSION_PATH; }; const RESPONSE_CODES = Object.freeze({ '00000': 'success', '40100': 'unauthorized', }); /* ---------- crypto ---------- */ // OpenSSL EVP_BytesToKey (MD5, tanpa salt) — sama seperti AES-128 password based. const evpBytesToKey = (password, keyLen = 16, ivLen = 16) => { const pass = Buffer.from(password, 'utf8'); let hash = Buffer.alloc(0); let data = Buffer.alloc(0); const out = []; while (Buffer.concat(out).length < keyLen + ivLen) { data = Buffer.concat([hash, pass]); hash = crypto.createHash('md5').update(data).digest(); out.push(hash); } const full = Buffer.concat(out); return { key: full.subarray(0, keyLen), iv: full.subarray(keyLen, keyLen + ivLen) }; }; const encryptPayload = (plain, password = ENC_PASSWORD) => { const { key, iv } = evpBytesToKey(password); const cipher = crypto.createCipheriv('aes-128-ofb', key, iv); return Buffer.concat([cipher.update(String(plain), 'utf8'), cipher.final()]).toString('base64'); }; const decryptPayload = (b64, password = ENC_PASSWORD) => { const { key, iv } = evpBytesToKey(password); const d = crypto.createDecipheriv('aes-128-ofb', key, iv); return Buffer.concat([d.update(Buffer.from(b64, 'base64')), d.final()]).toString('utf8'); }; const timestampUtc = (d = new Date()) => d.toISOString().replace(/\.\d{3}Z$/, 'Z'); const authHeaders = (accessToken, idToken, ts = timestampUtc()) => ({ accessAuthorization: 'Bearer ' + encryptPayload(JSON.stringify({ accessToken, timestamp: ts })), authorization: 'Bearer ' + encryptPayload(JSON.stringify({ token: idToken, timestamp: ts })), }); const randomHex = (n) => crypto.randomBytes(n).toString('hex'); const transactionId = (d = new Date()) => { const p = (v) => String(v).padStart(2, '0'); const stamp = String(d.getFullYear()).slice(2) + p(d.getMonth() + 1) + p(d.getDate()) + p(d.getHours()) + p(d.getMinutes()) + p(d.getSeconds()) + '000000'; return `A${stamp}148700`; }; const tselMsisdn62 = (v) => { const d = String(v ?? '').replace(/\D/g, ''); if (d.startsWith('62')) return d; if (d.startsWith('0')) return `62${d.slice(1)}`; return `62${d}`; }; class TselError extends Error { constructor(message, { code = 'TSEL_ERROR', status = null, details = null } = {}) { super(message); this.name = 'TselError'; this.code = code; this.status = status; this.details = details; } } const ciamUrl = () => `${CIAM}/iam/v1/realms/${REALM}/authenticate?authIndexType=service&authIndexValue=phoneLogin`; const webHeaders = () => ({ 'user-agent': UA, accept: 'application/json', 'accept-language': 'id-ID,id;q=0.9,en-US;q=0.8,en;q=0.7', dnt: '1', origin: 'https://my.telkomsel.com', referer: 'https://my.telkomsel.com/', 'content-type': 'application/json', }); const pickCookie = (res, name) => { const all = res.headers.getSetCookie ? res.headers.getSetCookie() : [res.headers.get('set-cookie') || '']; for (const c of all) if (c && c.startsWith(name + '=')) return c.split(';')[0]; return ''; }; class MyTelkomselClient { constructor({ msisdn, accessToken = null, idToken = null, cookies = {}, xDevice = null } = {}) { this.msisdn = tselMsisdn62(msisdn); this.accessToken = accessToken; this.idToken = idToken; this.cookies = cookies; // { amlbcookie, iPlanetDirectoryPro } this.xDevice = xDevice || `${randomHex(4)}-${randomHex(2)}-${randomHex(2)}-${randomHex(2)}-${randomHex(6)}`; this.authId = null; this.raw = {}; } get loggedIn() { return Boolean(this.accessToken && this.idToken); } /* ---- step 1: minta OTP ---- */ async requestOtp() { const res = await fetch(ciamUrl(), { method: 'POST', headers: { ...webHeaders(), 'am-phonenumber': '+' + this.msisdn, 'am-clientid': CLIENT_ID, 'am-send': 'otp', }, body: '', }); const text = await res.text(); let json = null; try { json = JSON.parse(text); } catch { /* html error page */ } this.cookies.amlbcookie = pickCookie(res, 'amlbcookie') || this.cookies.amlbcookie || ''; if (!res.ok || !json?.authId) { throw new TselError('requestOtp gagal', { code: 'otp_request_failed', status: res.status, details: text.slice(0, 300) }); } this.authId = json.authId; return { ok: true, authId: json.authId, status: res.status, callbacks: json.callbacks, amlbcookie: this.cookies.amlbcookie }; } /* ---- step 2-4: submit OTP -> code -> token ---- */ async submitOtp(otp) { if (!this.authId) throw new TselError('panggil requestOtp() dulu', { code: 'no_auth_id' }); const body = { authId: this.authId, callbacks: [ { type: 'PasswordCallback', output: [{ name: 'prompt', value: 'One Time Password' }], input: [{ name: 'IDToken1', value: String(otp) }], }, { type: 'ConfirmationCallback', output: [ { name: 'prompt', value: '' }, { name: 'messageType', value: 0 }, { name: 'options', value: ['Submit OTP', 'Request OTP'] }, { name: 'optionType', value: -1 }, { name: 'defaultOption', value: 0 }, ], input: [{ name: 'IDToken2', value: 0 }], }, ], }; const r2 = await fetch(ciamUrl(), { method: 'POST', headers: { ...webHeaders(), 'am-clientid': CLIENT_ID, ...(this.cookies.amlbcookie ? { cookie: this.cookies.amlbcookie } : {}), }, body: JSON.stringify(body), }); const t2 = await r2.text(); let j2 = null; try { j2 = JSON.parse(t2); } catch { /* ignore */ } if (!r2.ok) throw new TselError('submitOtp ditolak', { code: 'otp_rejected', status: r2.status, details: t2.slice(0, 300) }); if (!j2?.tokenId) throw new TselError('OTP salah / tanpa tokenId', { code: 'otp_wrong', status: r2.status, details: t2.slice(0, 300) }); const iPlanet = pickCookie(r2, 'iPlanetDirectoryPro') || `iPlanetDirectoryPro=${j2.tokenId}`; this.cookies.iPlanetDirectoryPro = iPlanet; const qs = new URLSearchParams({ client_id: CLIENT_ID, nonce: 'true', redirect_uri: REDIRECT_URI, response_type: 'code', scope: 'profile openid phone identifier', }); const r3 = await fetch(`${CIAM}/iam/v1/oauth2/realms/${REALM}/authorize?${qs}`, { method: 'GET', redirect: 'manual', headers: { 'user-agent': UA, accept: 'application/json', referer: 'https://my.telkomsel.com/', cookie: [this.cookies.amlbcookie, iPlanet].filter(Boolean).join('; '), }, }); const location = r3.headers.get('location') || ''; const code = location ? new URL(location, 'https://x').searchParams.get('code') : null; if (!code) throw new TselError('gagal ambil ?code dari redirect', { code: 'no_code', status: r3.status, details: location.slice(0, 300) }); const tq = new URLSearchParams({ client_id: CLIENT_ID, client_secret: CLIENT_SECRET, code, grant_type: 'authorization_code', redirect_uri: REDIRECT_URI, response_type: 'code', }); const r4 = await fetch(`${CIAM}/iam/v1/oauth2/realms/${REALM}/access_token?${tq}`, { method: 'POST', headers: { 'user-agent': UA, accept: 'application/json', 'content-type': 'application/x-www-form-urlencoded', origin: 'https://my.telkomsel.com', referer: 'https://my.telkomsel.com/', }, body: '', }); const t4 = await r4.text(); let j4 = null; try { j4 = JSON.parse(t4); } catch { /* ignore */ } if (!r4.ok || !j4?.access_token) { throw new TselError('gagal tukar code jadi access_token', { code: 'token_failed', status: r4.status, details: t4.slice(0, 300) }); } this.accessToken = j4.access_token; this.idToken = j4.id_token || j4.access_token; return { ok: true, accessToken: this.accessToken, idToken: this.idToken, expiresIn: j4.expires_in ?? null }; } /* ---- login lengkap kalau OTP sudah ada di tangan ---- */ static async login(msisdn, otp) { const client = new MyTelkomselClient({ msisdn }); const sent = await client.requestOtp(); if (!otp) return { client, sent, tokens: null }; const tokens = await client.submitOtp(otp); return { client, sent, tokens }; } static fromSession({ msisdn, accessToken, idToken, cookies = {}, xDevice }) { return new MyTelkomselClient({ msisdn, accessToken, idToken, cookies, xDevice }); } session() { return { msisdn: this.msisdn, accessToken: this.accessToken, idToken: this.idToken, cookies: this.cookies, xDevice: this.xDevice }; } /* ---- API call ke tdw ---- */ async call(method, path, body = null, { doubleBearer = false, allowEmpty = false } = {}) { if (!this.loggedIn) throw new TselError('belum login', { code: 'not_logged_in' }); const { accessAuthorization, authorization } = authHeaders(this.accessToken, this.idToken); const wrap = (v) => (doubleBearer ? 'Bearer ' + v : v); const headers = { accept: 'application/json', 'accept-language': 'id-ID,id;q=0.9,en-US;q=0.8,en;q=0.7', accessauthorization: wrap(accessAuthorization), authorization: wrap(authorization), authserver: '2', channelid: 'WEB', 'content-type': 'application/json', dnt: '1', hash: randomHex(28), language: 'id', 'mytelkomsel-web-app-version': WEB_VERSION, origin: 'https://my.telkomsel.com', referer: 'https://my.telkomsel.com/', transactionid: transactionId(), 'user-agent': UA, 'web-msisdn': this.msisdn, 'x-device': this.xDevice, }; const res = await fetch(API + path, { method, headers, body: method === 'GET' ? undefined : JSON.stringify(body ?? {}), }); const text = await res.text(); let json = null; try { json = JSON.parse(text); } catch { /* ignore */ } if (!res.ok) throw new TselError(`HTTP ${res.status} ${path}`, { code: 'http_error', status: res.status, details: text.slice(0, 400) }); if (json?.status && json.status !== '00000' && !(allowEmpty && json.status === '00001')) { throw new TselError(`${path}: ${json.message}`, { code: json.status, status: res.status, details: json }); } return { ok: true, status: res.status, data: json?.data ?? json, raw: json }; } profile() { return this.call('GET', '/api/attributes/getprofile'); } loyalty() { return this.call('GET', '/api/subscriber/loyalty-info'); } quota() { return this.call('POST', '/api/subscriber/v5/bonuses', { isPrepaid: true, location: '', roaming: false }); } offers() { return this.call('POST', '/api/offers/recommended/v2', { isPrepaid: true, page: 'dashboard', isCorporate: false, fetchSpecialAreaPackage: true, isRoaming: false, }); } packageDetails(offerId) { return this.call('GET', `/api/paket-details/v2/${offerId}`); } buy({ offerId, paymentMethod = 'qris', toBeSubscribedTo = false }) { return this.call('POST', '/api/payment/fulfillment/v2', { mode: 'SELF', productType: 'PACKAGE', msisdninitiator: this.msisdn, toBeSubscribedTo, platform: 'web', type: 'purchase', offerID: offerId, paymentMethod, businessproductid: offerId, isCampaignOffer: 'false', cart_id: '', }); } paymentStatus(orderId) { return this.call('POST', '/api/payment/status', { orderid: orderId }); } /* ---- lapisan ternormalisasi (dipakai CLI) ---- */ async dashboard() { const [profile, balance, quota, loyalty] = await Promise.allSettled([ this.profile(), this.call('GET', '/api/subscriber/profile-balance'), this.quota(), this.loyalty(), ]); const ok = (r) => (r.status === 'fulfilled' ? r.value.data : null); return { profile: ok(profile), balance: ok(balance), quota: ok(quota), loyalty: ok(loyalty) }; } async packages() { const r = await this.offers(); return offerListOf(r.data); } async packageDetail(offerId) { const r = await this.packageDetails(offerId); return r.data; } /** Tier, LOS, ARPU — dari HVC (butuh platform). */ async info(platform = 'web') { const r = await this.call('GET', `/api/subscriber/hvc/v2/information?platform=${platform}`); return r.data; } /** Riwayat poin per bulan (butuh page; size tidak diizinkan). */ async pointHistory(page = 1) { const r = await this.call('GET', `/api/poin-catalog/history/v2?page=${page}`); return r.data ?? {}; } /** Profil lengkap (v5): brand, priceplan, grace/cancel date, PUK. */ async profileFull() { const r = await this.call('GET', '/api/subscriber/v5/profile'); return { ...(r.data ?? {}) }; } /** Katalog voucher game (75 game). */ async games() { const r = await this.call('GET', '/api/voucher-games/v1/list?page=1&limit=100'); return (r.data?.voucherGames ?? []).map((g) => ({ id: g.id, name: g.name, product: g.gameName, ref: g.product_ref, price: Number(g.startPrice ?? g.priceDefault ?? 0), slug: g.slug, })); } /** Katalog reward Telkomsel Poin (10 per halaman). */ async rewards(page = 1, category = '') { const q = `?page=${page}${category ? '&category=' + encodeURIComponent(category) : ''}`; const r = await this.call('GET', '/api/poin-catalog/v4/' + q); const d = r.data ?? {}; return { page: Number(page), pageCount: d.pageCount ?? 1, list: d.rewards ?? [] }; } /** Riwayat transaksi (kosong = belum ada catatan di server). */ async history() { const r = await this.call('GET', '/api/payment-history', null, { allowEmpty: true }); const d = r.data; return Array.isArray(d) ? d : (d?.data ?? []); } /** Voucher fisik (13 nominal) yang bisa dibeli. */ async vouchers() { const r = await this.call('GET', '/api/prepaid-vouchers/v3/'); const d = r.data ?? {}; return (d.vouchers ?? []).map((v) => ({ id: v.id, name: v.name, cost: Number(v.cost ?? 0), validity: v.validity, points: v.points, })); } } /* ---------- normalisasi ---------- */ const quotaListOf = (data) => { const groups = data?.userBonuses ?? []; return groups.map((g) => ({ class: g.class, total: g.totalText, items: (g.bonusList ?? []).map((b) => ({ name: b.name || b.bucketdescription, remaining: b.remainingquota, remainingValue: b.remainingquotaValue, expiry: b.expirydate, orderId: b.order_id, })), })); }; const offerListOf = (data) => { const out = []; const seen = new Set(); for (const g of data?.offerGroup ?? []) { for (const o of g.offer ?? []) { if (seen.has(o.id)) continue; seen.add(o.id); out.push({ id: o.id, name: o.name, price: o.price, validity: o.productlength, highlight: o.highlightvalue, category: o.category, isLoan: Boolean(o.isLoan), isSubscribe: Boolean(o.isSubscribe), bonus: (o.bonus ?? []).map((b) => `${b.name} ${b.quota}`.trim()), }); } } return out; }; const formatQuota = (groups) => { if (!groups?.length) return 'Tidak ada data kuota.'; return groups.map((g) => { const head = `[${g.class}] total ${g.total ?? '-'}`; const lines = g.items.map((i) => ` • ${i.name}: ${i.remaining} (exp ${i.expiry ?? '-'})`); return [head, ...lines].join('\n'); }).join('\n\n'); }; /* ============================ UI ============================ */ // NYX PROJECT — terminal toolkit (modul: bima / Tri-IOH) // Author : Akwila Dimas // GitHub : https://github.com/Akwds01 // Telegram: https://t.me/nyx_projectss · https://t.me/NYX_PROJECTS // WhatsApp: https://whatsapp.com/channel/0029VbEMMAQHbFUzKKOE5o0Y // Sumber / referensi: // - https://github.com/vermaysha/bima-plus // - https://github.com/0xtbug/telbot // - https://github.com/Najihh/EnQuota // - https://gist.github.com/ayashiiiyo/e2561dddd66e1259a17b3eac28c47b55 (myIM3) // Detail di CLI: `nyx about` · link: `nyx links` /* Mode interaktif: banner → login → menu bernomor. Dipakai oleh cli.mjs. */ const ART = ` ███╗ ██╗██╗ ██╗██╗ ██╗ ████╗ ██║╚██╗ ██╔╝╚██╗██╔╝ ██╔██╗ ██║ ╚████╔╝ ╚███╔╝ ██║╚██╗██║ ╚██╔╝ ██╔██╗ ██║ ╚████║ ██║ ██╔╝ ██╗ ╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝`; async function runInteractive(ctx) { const { C, pad, rupiah, localMsisdn, BimaClient, loadSession, saveSession, balanceOf, activePackagesOf, quotasOf, catalogOf, rewardsOf, ENDPOINTS, } = ctx; const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: process.stdin.isTTY }); class Exit extends Error {} // Antrean baris sendiri: readline.question() bisa menggantung saat stdin pipa/EOF. const antre = []; const tunggu = []; rl.on('line', (l) => { const w = tunggu.shift(); if (w) w.resolve(l); else antre.push(l); }); rl.on('close', () => { while (tunggu.length) tunggu.shift().reject(new Exit()); }); const ask = (q) => { process.stdout.write(q); if (antre.length) return Promise.resolve(antre.shift()); return new Promise((resolve, reject) => tunggu.push({ resolve, reject })); }; const OK = ctx.PLAIN ? '[ok]' : '✓'; const pause = async () => { await ask(C.dim(ctx.PLAIN ? '\n [Enter] kembali ' : '\n ↵ Enter untuk kembali ')); }; const banner = () => { if (ctx.PLAIN) { console.log(''); console.log(' ================================'); console.log(' N Y X P R O J E C T'); console.log(' terminal toolkit'); console.log(' ================================'); } else { console.log(C.cyan(ART)); console.log(C.dim(' NYX PROJECT · terminal toolkit')); console.log(C.dim(' modul: ' + (ctx.tsel ? 'bima (Tri/IOH) · tsel (Telkomsel)' : 'bima (Tri/IOH)'))); console.log(C.dim(` ${ctx.creditLine()}`)); const refs = ctx.BRAND.refs.map(([n]) => n).join(', '); console.log(C.dim(' sumber: ' + refs)); console.log(C.dim(' detail: nyx about · link: nyx links')); console.log(C.dim(' ' + (ctx.PLAIN ? '-'.repeat(46) : '─'.repeat(46)))); } }; /* -------------------------------------------------------- aksi menu */ const showStatus = async (client) => { await ctx.statusCard(client); }; const listPackages = async (client, buy) => { const catid = await pilihSub(client); if (!catid) return; const semua = await ambilKatalog(client, catid); if (!semua.length) { console.log(C.yellow(' Tidak ada paket di kategori ini untuk nomormu.')); return; } const judul = catid === '31' ? 'Semua paket data' : (subsCache?.find((x) => x.id === catid)?.title ?? 'Paket'); let list = semua; let page = 0; const per = 12; let cari = ''; for (;;) { const total = Math.max(1, Math.ceil(list.length / per)); const shown = list.slice(page * per, page * per + per); console.log('\n' + C.bold(` ${judul}${cari ? ` — cari "${cari}"` : ''}`) + C.dim(` (${list.length} paket, urut termurah)`)); shown.forEach((p, i) => { console.log(` ${String(page * per + i + 1).padStart(3)}. ${pad(p.name, 26)} ${pad(rupiah(p.price), 11)} ${C.dim(p.validity ?? '')}`); }); console.log(C.dim(` hal ${page + 1}/${total} · nomor · n/p · s cari · k=ganti kategori · 0=kembali`)); const pick = (await ask('\n > ')).trim().toLowerCase(); if (pick === '0' || pick === '') return; if (pick === 'n') { page = Math.min(page + 1, total - 1); continue; } if (pick === 'p') { page = Math.max(page - 1, 0); continue; } if (pick === 'k') { return listPackages(client, buy); } if (pick.startsWith('s')) { cari = pick.slice(1).trim(); list = cari ? semua.filter((p) => p.name.toLowerCase().includes(cari)) : semua; page = 0; continue; } const idx = page * per + Number(pick) - 1; if (!Number.isInteger(idx) || idx < 0 || idx >= list.length) { console.log(C.dim(' Pilihan tidak dikenal.')); continue; } const p = list[idx]; if (!buy) { console.log(`\n ${C.bold(p.name)} ${rupiah(p.price)} ${p.validity ?? ''}`); console.log(` kode ${p.pvrCode} · ${C.dim(p.channels || '-')}`); continue; } const yes = (await ask(` Beli ${C.bold(p.name)} ${rupiah(p.price)} lewat QRIS? (y/N): `)).trim().toLowerCase(); if (yes !== 'y') { console.log(C.dim(' Dibatalkan.')); return; } console.log(' ' + C.dim('Membuat tagihan QRIS…')); const validity = String(p.validity ?? '1').match(/\d+/)?.[0] ?? '1'; const order = await client.buyQris({ pvrCode: p.pvrCode, keyword: p.keyword, packageName: p.name, price: p.price, validity, channel: 'QRIS' }); console.log(C.green(`\n ✓ Tagihan dibuat (${order.expiryMinutes} menit)`) + C.dim(' ' + order.transid)); console.log('\n ' + C.bold('QR — buka, screenshot, bayar dari galeri:')); console.log(' ' + C.cyan(order.imageUrl)); console.log(C.dim('\n e-wallet / m-banking → Scan QRIS → pilih gambar dari galeri.')); return; } }; const showQris = async (client) => { const list = await client.pendingQrisOrders(); if (!list.length) { console.log('\n Tidak ada tagihan pending.'); return; } console.log('\n' + C.bold(` Tagihan pending (${list.length})`)); for (const o of list) { console.log(` • ${pad(o.product ?? '-', 22)} ${pad(rupiah(o.amount), 12)} ${C.dim(o.createdAt ?? '')}`); console.log(' ' + C.cyan(o.imageUrl)); } }; const listDarurat = async (client, activate) => { const j = await client.emgList(); const list = j.data?.servicelist ?? (j.data?.serviceList ?? []); console.log('\n' + C.bold(' Paket Darurat (SOS)') + C.dim(' biaya ditagih menyusul')); list.forEach((s, i) => { const ok = /eligible/i.test(String(s.sos?.eligible)) || String(s.sos?.eligibilitystatus).toUpperCase() === 'ELIGIBLE'; console.log(` ${String(i + 1).padStart(2)}. ${pad(s.name, 32)} ${pad(rupiah(s.price), 11)} ${ok ? C.green('eligible') : C.dim('—')}`); }); if (!activate) return; const n = Number((await ask('\n Nomor paket darurat (0 = batal): ')).trim()); if (!n || n < 1 || n > list.length) { console.log(C.dim(' Dibatalkan.')); return; } const s = list[n - 1]; const yes = (await ask(` Aktifkan ${C.bold(s.name)} ${rupiah(s.price)}? ditagih menyusul (y/N): `)).trim().toLowerCase(); if (yes !== 'y') { console.log(C.dim(' Dibatalkan.')); return; } const r = await client.activateEmergency({ actioncode: s.actioncode, name: s.name, price: s.price, amount: s.sos?.amount, fee: s.sos?.fee, period: s.sos?.period, periodUnit: s.sos?.periodunit, }); console.log(String(r.status) === '0' ? C.green('\n ✓ Aktif: ' + s.name) : C.yellow('\n Respons: ' + (r.message ?? ''))); console.log(C.dim(' Cek lewat menu 1.')); }; const showPoin = async (client) => { const d = (await client.points()).data ?? {}; console.log('\n' + C.bold(' BonsTri')); console.log(` Poin : ${C.green(String(d.redeemablepoints ?? 0))} ${C.dim('(tier ' + (d.tierlevel ?? '-') + ')')}`); console.log(` Hangus : ${d.expireson ?? '-'} (${d.pointstoexpire ?? 0} poin)`); const rows = rewardsOf((await client.rewards()).data ?? {}) .filter((x) => x.points > 0 && x.points <= Number(d.redeemablepoints ?? 0)) .sort((a, b) => a.points - b.points); console.log('\n' + C.bold(` Bisa ditukar (${rows.length})`)); rows.slice(0, 8).forEach((x) => console.log(` ${pad(x.points + ' poin', 9)} ${pad(x.name, 44)} ${C.dim('id ' + x.id)}`)); console.log(C.dim('\n Tukar di aplikasi bima+ (endpoint /lms/redeem sedang error di server).')); }; const showNotif = async (client) => { const j = await client.notifications(); const list = Array.isArray(j.data) ? j.data : (j.data?.notifications ?? []); console.log('\n' + C.bold(` Notifikasi (${list.length})`)); list.slice(0, 8).forEach((n) => console.log(' • ' + String(n.summary ?? n.title ?? '').replace(/\s+/g, ' ').slice(0, 88))); }; const showRiwayat = async (client) => { const tx = (await client.history()).data?.transactions ?? []; console.log('\n' + C.bold(` Riwayat (${tx.length})`)); tx.slice(0, 8).forEach((t) => { const bad = /fail/i.test(String(t.status)); console.log(` ${pad(t.datetime ?? '', 19)} ${pad(t.productname || '-', 18)} ${pad(t.price ?? '', 8)} ${pad(t.paymentmethod ?? '', 7)} ${bad ? C.red(t.status) : C.green(t.status)}`); }); }; /* ------------------------------------------------------ onboarding */ const loginFlow = async () => { console.log('\n ' + C.bold('Masuk ke akun Tri')); const number = (await ask(' Nomor Tri (mis. 089612345678): ')).trim(); if (!number) { console.log(C.red(' Nomor kosong.')); return null; } const client = new BimaClient({ msisdn: number }); console.log(' ' + C.dim('Meminta OTP…')); const { transid } = await client.requestOtp(); console.log(C.green(' ✓ OTP dikirim ke ') + localMsisdn(client.msisdn)); const otp = (await ask(' Kode OTP: ')).trim(); if (!otp) return null; await client.submitOtp(otp, transid); saveSession(client.session()); console.log(C.green(' ✓ Login berhasil, sesi disimpan.')); return BimaClient.fromSession(client.session()); }; /* ------------------------------------------------------------ utama */ banner(); const bimaMenu = async () => { let client = null; const saved = loadSession(); if (saved?.tokenId) { client = BimaClient.fromSession(saved); console.log('\n ' + C.green(OK) + ' Sesi aktif: ' + C.bold(localMsisdn(saved.msisdn))); try { const d = (await client.dashboard()).data; console.log(C.dim(` pulsa ${rupiah(balanceOf(d))} · ${activePackagesOf(d).length} paket aktif`)); } catch { console.log(C.yellow(' Sesi tidak valid, login ulang diperlukan.')); client = null; } } if (!client) { try { client = await loginFlow(); } catch (e) { console.error(C.red(' ✖ ' + (e.message || e))); } if (!client) { console.log(C.dim(' Kembali ke pilihan modul.')); return; } } try { for (;;) { console.log('\n' + C.bold(ctx.PLAIN ? ' -- Menu --' : ' ── Menu ──')); console.log(' 1. Ringkasan akun (pulsa, kuota, paket)'); console.log(' 2. Katalog paket'); console.log(' 3. Beli paket (QRIS)'); console.log(' 4. Tagihan QRIS pending'); console.log(' 5. Paket darurat (SOS)'); console.log(' 6. BonsTri & reward'); console.log(' 7. Notifikasi'); console.log(' 8. Riwayat transaksi'); console.log(' 9. Ganti nomor / login ulang'); console.log(' 10. Promo personal (diskon)'); console.log(' 11. Tentang NYX (author, sumber)'); console.log(' 0. Keluar'); const pick = (await ask('\n Pilih: ')).trim(); try { switch (pick) { case '1': await showStatus(client); await pause(); break; case '2': await listPackages(client, false); await pause(); break; case '3': await listPackages(client, true); await pause(); break; case '4': await showQris(client); await pause(); break; case '5': await listDarurat(client, true); await pause(); break; case '6': await showPoin(client); await pause(); break; case '7': await showNotif(client); await pause(); break; case '8': await showRiwayat(client); await pause(); break; case '9': { const c2 = await loginFlow(); if (c2) client = c2; break; } case '11': { const B = ctx.BRAND; console.log('\n' + C.bold(` ${B.name} v${B.version} · ${B.tagline}`)); console.log(` Author : ${B.author}`); console.log(` GitHub : ${B.github || '—'}`); console.log(` WhatsApp : ${B.waChannel || '— belum diisi'}`); console.log(` Telegram : ${B.telegram || '—'} (channel)`); if (B.telegramPersonal) console.log(` Kontak : ${B.telegramPersonal}`); console.log('\n ' + C.bold('Sumber & referensi')); for (const [n, u] of B.refs) console.log(` • ${n}\n ${C.dim(u)}`); await pause(); break; } case '10': { const list = await client.promotions(); if (!list.length) { console.log('\n Tidak ada penawaran personal.'); break; } console.log('\n' + C.bold(` Penawaran khusus ${localMsisdn(client.msisdn)} (${list.length})`)); list.forEach((x, i) => console.log(` ${String(i + 1).padStart(2)}. ${pad(x.name, 28)} ${pad(rupiah(x.price), 11)} ${pad(x.validity ?? '', 9)} ${C.dim(x.pvrCode)}`)); const n = Number((await ask('\n Beli nomor (0 = batal): ')).trim()); if (n >= 1 && n <= list.length) { const x = list[n - 1]; const yes = (await ask(` Beli ${C.bold(x.name)} ${rupiah(x.price)} lewat QRIS? (y/N): `)).trim().toLowerCase(); if (yes === 'y') { const order = await client.buyQris({ pvrCode: x.pvrCode, keyword: x.keyword, packageName: x.name, price: x.price, validity: String(x.validity ?? '1').match(/\d+/)?.[0] ?? '1', channel: 'QRIS' }); console.log(C.green(`\n ✓ Tagihan dibuat (${order.expiryMinutes} menit)`) + C.dim(' ' + order.transid)); console.log(' ' + C.cyan(order.imageUrl)); } else console.log(C.dim(' Dibatalkan.')); } await pause(); break; } case '0': case 'q': case 'exit': console.log(C.dim(' Kembali ke pilihan modul.')); rl.close(); return; default: console.log(C.dim(' Pilihan tidak dikenal.')); } } catch (e) { if (e instanceof Exit) { console.log(C.dim(' Kembali ke pilihan modul.')); return; } console.error(C.red('\n ✖ ' + (e.message || String(e))) + (e.code ? C.dim(` [${e.code}]`) : '')); } } } catch (e) { if (e instanceof Exit) throw e; throw e; } }; /* ------------------------------------------------------ menu tsel */ const tselMenu = async () => { const T = ctx.tsel; if (!T) { console.log(C.yellow(' Modul tsel tidak tersedia.')); return; } if (!T.hasSession()) { console.log('\n ' + C.bold('Masuk ke akun Telkomsel')); const nomor = (await ask(' Nomor Telkomsel (mis. 081225126143): ')).trim(); if (!nomor) return; try { await T.login(nomor); const otp = (await ask(' Kode OTP: ')).trim(); if (!otp) return; await T.verify(otp); } catch (e) { console.log(C.red(' ✖ ' + (e.message || e))); return; } } for (;;) { console.log('\n' + C.bold(ctx.PLAIN ? ' -- Menu tsel --' : ' ── Menu tsel ──')); console.log(' 1. Ringkasan akun (pulsa, masa aktif, poin, kuota)'); console.log(' 2. Daftar paket'); console.log(' 3. Beli paket (QRIS)'); console.log(' 4. Info pelanggan (tier, ARPU)'); console.log(' 5. Profil kartu (brand, masa aktif)'); console.log(' 6. Telkomsel Poin & mutasi'); console.log(' 7. Katalog reward (tukar poin)'); console.log(' 8. Voucher fisik'); console.log(' 9. Voucher game'); console.log(' 10. Riwayat transaksi'); console.log(' 11. Login ulang / ganti nomor'); console.log(' 0. Kembali ke pilihan modul'); const pick = (await ask('\n Pilih: ')).trim(); try { if (pick === '1') { await T.status(); await pause(); } else if (pick === '2') { await T.paket(); await pause(); } else if (pick === '3') { await T.paket(); const id = (await ask('\n ID paket (kosong = batal): ')).trim(); if (!id) { console.log(C.dim(' Dibatalkan.')); continue; } const yes = (await ask(' Buat tagihan QRIS? (y/N): ')).trim().toLowerCase(); if (yes === 'y') await T.beli(id, 'qris'); else console.log(C.dim(' Dibatalkan.')); await pause(); } else if (pick === '4') { await T.info(); await pause(); } else if (pick === '5') { await T.profil(); await pause(); } else if (pick === '6') { await T.poin(); await pause(); } else if (pick === '7') { await T.reward(1, ''); await pause(); } else if (pick === '8') { await T.voucher(); await pause(); } else if (pick === '9') { await T.game(); await pause(); } else if (pick === '10') { await T.riwayat(); await pause(); } else if (pick === '11') { T.logout(); console.log(C.dim(' Sesi dihapus. Login lagi lewat menu ini.')); return; } else if (pick === '0' || pick === '') return; else console.log(C.dim(' Pilihan tidak dikenal.')); } catch (e) { if (e instanceof Exit) throw e; console.error(C.red('\n ✖ ' + (e.message || String(e))) + (e.code ? C.dim(' [' + e.code + ']') : '')); } } }; /* --------------------------------------------------- pilih modul */ const aboutBlock = () => { const B = ctx.BRAND; console.log('\n' + C.bold(' ' + B.name + ' v' + B.version + ' · ' + B.tagline)); console.log(' Author : ' + B.author); console.log(' GitHub : ' + (B.github || '—')); console.log(' WhatsApp : ' + (B.waChannel || '—')); console.log(' Telegram : ' + (B.telegram || '—') + ' (channel)'); if (B.telegramPersonal) console.log(' Kontak : ' + B.telegramPersonal); console.log('\n ' + C.bold('Sumber & referensi')); for (const [n, u] of B.refs) console.log(' • ' + n + '\n ' + C.dim(u)); }; try { for (;;) { console.log('\n' + C.bold(ctx.PLAIN ? ' -- Pilih modul --' : ' ── Pilih modul ──')); console.log(' 1. bima — Tri / IOH (Bima+)'); if (ctx.tsel) console.log(' 2. tsel — Telkomsel (MyTelkomsel)'); console.log(' 3. Tentang NYX (author, sumber)'); console.log(' 0. Keluar'); const pick = (await ask('\n Pilih: ')).trim(); if (pick === '0' || pick === 'q' || pick === 'exit') break; if (pick === '1') await bimaMenu(); else if (pick === '2' && ctx.tsel) await tselMenu(); else if (pick === '3') { aboutBlock(); await pause(); } else console.log(C.dim(' Pilihan tidak dikenal.')); } } catch (e) { if (!(e instanceof Exit)) throw e; } console.log('\n ' + C.dim('Sampai jumpa.') + '\n'); rl.close(); } /* ============================ CLI ============================ */ // NYX PROJECT — terminal toolkit (modul: bima / Tri-IOH) // Author : Akwila Dimas // GitHub : https://github.com/Akwds01 // Telegram: https://t.me/nyx_projectss · https://t.me/NYX_PROJECTS // WhatsApp: https://whatsapp.com/channel/0029VbEMMAQHbFUzKKOE5o0Y // Sumber / referensi: // - https://github.com/vermaysha/bima-plus // - https://github.com/0xtbug/telbot // - https://github.com/Najihh/EnQuota // - https://gist.github.com/ayashiiiyo/e2561dddd66e1259a17b3eac28c47b55 (myIM3) // Detail di CLI: `nyx about` · link: `nyx links` // License : MIT (2026, Akwila Dimas) — bebas dipakai/diubah/dibagikan dengan notice const rawArgs = process.argv.slice(2); // NUSA: `nusa bima status` == `nusa status` (nama provider boleh disebut dulu) const PROVIDERS = new Set(['bima', 'bimaplus', 'tri', 'ioh', 'nyx', 'tsel', 'telkomsel']); const isTsel = ['tsel', 'telkomsel'].includes(String(rawArgs[0] ?? '').toLowerCase()); if (PROVIDERS.has(String(rawArgs[0] ?? '').toLowerCase())) rawArgs.shift(); const argv = rawArgs; const flags = new Set(argv.filter((a) => a.startsWith('--'))); // flag yang butuh nilai: nilai setelahnya jangan dianggap argumen posisional const VALUE_FLAGS = new Set(['--maks', '--channel', '--cat', '--session', '--cari', '--kategori', '--sisir']); const args = []; for (let i = 0; i < argv.length; i++) { const a = argv[i]; if (VALUE_FLAGS.has(a)) { i++; continue; } if (a.startsWith('--')) continue; args.push(a); } const flagValue = (name) => { const i = argv.indexOf(name); return i >= 0 ? argv[i + 1] : null; }; const cmd = (args[0] || '').toLowerCase(); const rest = args.slice(1); const asJson = flags.has('--json'); const dryRun = flags.has('--dry'); const curlOut = flags.has('--curl'); // Tampilan kaya (kotak + warna) dipakai di semua OS. Di Windows console dipaksa // UTF-8 supaya karakter garis tampil benar; ASCII polos hanya kalau diminta manual. const PLAIN = process.env.NYX_PLAIN === '1' || process.env.NYX_ASCII === '1'; if (process.platform === 'win32') { try { spawnSync('chcp.com', ['65001'], { stdio: 'ignore' }); } catch {} } const BOX = PLAIN ? { tl: '+', tr: '+', bl: '+', br: '+', h: '-', v: '|' } : { tl: '┌', tr: '┐', bl: '└', br: '┘', h: '─', v: '│' }; const C = (process.stdout.isTTY && !PLAIN) ? { dim: (s) => `\x1b[2m${s}\x1b[0m`, bold: (s) => `\x1b[1m${s}\x1b[0m`, green: (s) => `\x1b[32m${s}\x1b[0m`, yellow: (s) => `\x1b[33m${s}\x1b[0m`, red: (s) => `\x1b[31m${s}\x1b[0m`, cyan: (s) => `\x1b[36m${s}\x1b[0m` } : { dim: (s) => s, bold: (s) => s, green: (s) => s, yellow: (s) => s, red: (s) => s, cyan: (s) => s }; const out = (obj) => { if (asJson) console.log(JSON.stringify(obj, null, 2)); }; const line = (s = '') => { if (!asJson) console.log(s); }; const pad = (s, n) => String(s).padEnd(n).slice(0, n); function needSession() { const s = loadSession(); if (!s?.tokenId) { console.error(C.red('Belum login.') + ' Jalankan: ' + C.bold('node cli.mjs login 08xxxxxxxxxx')); process.exit(2); } return BimaClient.fromSession(s); } function fail(err) { const e = (err && err.code) ? err : new BimaError(err.message); if (e.details && typeof e.details === 'string') { const d = e.details.replace(/\s+/g, ' ').slice(0, 240); console.error(C.dim(' detail: ' + d)); } console.error(C.red(`✖ ${e.message}`) + (e.code ? C.dim(` [${e.code}]`) : '')); process.exit(1); } const help = () => { line(C.bold('NYX PROJECT — terminal toolkit')); line(C.dim(` ${BRAND.author} · ${BRAND.github.replace(/^https?:\/\//, '')} · t.me/nyx_projectss`)); line(C.dim(` sumber: ${BRAND.refs.map(([n]) => n).join(', ')}`)); line(C.dim(' detail lengkap: nyx about · link: nyx links')); line(''); line(C.dim(' Jalankan `nyx` tanpa argumen untuk mode interaktif (menu).')); line(''); line(C.bold('Akun') + C.dim(' (login sekali, sesi disimpan di ' + SESSION_PATH + ')')); line(' login Kirim OTP ke nomor (0800..., 628... atau 800...)'); line(' verify Verifikasi OTP & simpan sesi'); line(' status Pulsa, kuota, paket aktif'); line(' poin BonsTri (poin, tier, kedaluwarsa)'); line(' reward [--maks N] Daftar reward yang bisa ditukar'); line(' notif Notifikasi terakhir'); line(' riwayat Riwayat transaksi'); line(''); line(C.bold('Katalog')); line(' paket [catid] [kata] Daftar paket; catid boleh subkategori (mis. 2383 Happy Harian)'); line(' paket --semua --maks N Tampilkan semua / batasi harga'); line(' kategori Daftar subkategori (Pasti Murah, Happy Harian, 5G, dst)'); line(' promo Penawaran personal/CVM (diskon khusus nomor)'); line(' detail Detail paket + channel bayar yang tersedia'); line(''); line(C.bold('Beli')); line(' beli [--channel QRIS] Buat tagihan QRIS (tampil gambar QR + payload)'); line(' qris Tagihan QRIS yang masih pending (link QR)'); line(' darurat Daftar paket darurat (SOS) yang bisa dipakai tanpa pulsa'); line(' darurat-beli Aktifkan paket darurat'); line(''); line(C.bold('Lanjutan')); line(' api \'{json}\' Panggil endpoint apa pun (mis. /profile/get \'{}\')'); line(' ... --curl Cetak perintah curl setara, tanpa mengirim'); line(''); line(C.bold('Opsi')); line(' --json Output JSON (untuk skrip)'); line(' --dry Tampilkan payload tanpa mengirim (khusus beli)'); line(''); line(C.dim('Contoh: nyx login 089612345678 → nyx verify 123456 → nyx status')); line(''); line(C.dim(' ' + creditLine())); line(C.dim(` ${BRAND.name} v${BRAND.version} · ${BRAND.tagline}`)); }; /* ------------------------------------------------------------------ akun */ async function doLogin(number) { if (!number) return fail(new Error('Nomor wajib: login ')); const client = new BimaClient({ msisdn: number }); const { transid } = await client.requestOtp(); const s = client.session(); saveSession({ ...s, pendingTransId: transid, pendingMsisdn: s.msisdn }); line(C.green('✓ OTP dikirim ke ' + localMsisdn(s.msisdn))); line(' transid: ' + C.dim(transid)); line(' Lanjut: ' + C.bold(`node cli.mjs verify `)); out({ ok: true, transid, msisdn: s.msisdn }); } async function doVerify(otp) { if (!otp) return fail(new Error('OTP wajib: verify ')); const s = loadSession(); if (!s?.pendingTransId) return fail(new Error('Tidak ada OTP yang menunggu. Jalankan `login ` dulu.')); const client = new BimaClient({ msisdn: s.pendingMsisdn, tokenId: s.tokenId, deviceId: s.deviceId, cookies: s.cookies }); await client.submitOtp(otp, s.pendingTransId); const saved = client.session(); saveSession(saved); line(C.green('✓ Login berhasil. Sesi disimpan.')); line(' Nomor: ' + localMsisdn(saved.msisdn)); out({ ok: true, msisdn: saved.msisdn }); } async function doStatus() { const c = needSession(); const info = await statusCard(c); out({ ok: true, ...info }); } async function doPoints() { const c = needSession(); const p = await c.points(); const d = p.data ?? {}; line(C.bold('BonsTri')); line(` Poin tersedia : ${C.green(String(d.redeemablepoints ?? 0))}`); line(` Tier : ${d.tierlevel ?? '-'}`); line(` Kedaluwarsa : ${d.expireson ?? '-'} (${d.pointstoexpire ?? 0} poin)`); line(` Loyalty ID : ${C.dim(d.loyaltyid ?? '-')}`); if (d.returnmsg) line(C.dim(' ' + d.returnmsg)); out({ ok: true, ...d }); } async function doRewards(maxPoints) { const c = needSession(); const r = await c.rewards(); const all = rewardsOf(r.data ?? {}); const max = maxPoints ? Number(maxPoints) : Infinity; const rows = all.filter((x) => x.points > 0 && x.points <= max).sort((a, b) => a.points - b.points); line(C.bold(`Reward tersedia (${rows.length} dari ${all.length})`) + (maxPoints ? C.dim(` · ≤ ${maxPoints} poin`) : '')); for (const x of rows.slice(0, 40)) line(` ${pad(x.points + ' poin', 9)} ${pad(x.name, 54)} ${C.dim('id ' + x.id)}`); out({ ok: true, rewards: rows }); } async function doNotif() { const c = needSession(); const j = await c.notifications(); const list = Array.isArray(j.data) ? j.data : (j.data?.notifications ?? []); line(C.bold(`Notifikasi (${list.length})`)); for (const n of list.slice(0, 10)) line(' • ' + String(n.summary ?? n.title ?? '').slice(0, 100)); out({ ok: true, notifications: list }); } async function doHistory() { const c = needSession(); const j = await c.history(); const tx = j.data?.transactions ?? []; line(C.bold(`Riwayat (${tx.length})`)); for (const t of tx.slice(0, 15)) { const bad = /fail/i.test(String(t.status)); line(` ${pad(t.datetime ?? '', 20)} ${pad(t.productname || '-', 22)} ${pad(t.price ?? '', 8)} ${pad(t.paymentmethod ?? '', 8)} ${bad ? C.red(t.status) : C.green(t.status)}`); } out({ ok: true, transactions: tx }); } /* --------------------------------------------------------------- katalog */ async function doPaket(catid = '31', kata = '', maks = null, semua = false) { const c = needSession(); const petakan = (raw) => catalogOf({ data: { commercial_package: raw } }); let raw = await c.packages(String(catid)); if (!raw.length) { const guest = new BimaClient({}); await guest.guest(); raw = await guest.packages(String(catid)); } let list = petakan(raw); if (!list.length) { line(C.yellow(`Kategori ${catid}: tidak ada paket untuk nomor ini`) + C.dim(' (bisa karena eligibility, segmen, atau sudah punya paket sejenis).')); return out({ ok: true, category: catid, total: 0, packages: [] }); } const seen = new Set(); list = list.filter((p) => p.pvrCode && !seen.has(p.pvrCode) && seen.add(p.pvrCode)); if (kata) list = list.filter((p) => p.name.toLowerCase().includes(String(kata).toLowerCase())); if (maks) list = list.filter((p) => p.price <= Number(maks)); list.sort((a, b) => a.price - b.price); const rows = semua ? list : list.slice(0, 40); line(C.bold(`Paket kategori ${catid}${kata ? ` · cari "${kata}"` : ''}${maks ? ` · ≤ ${rupiah(maks)}` : ''} — ${list.length} paket`)); for (const p of rows) line(` ${pad(p.pvrCode, 7)} ${pad(p.name, 26)} ${pad(rupiah(p.price), 11)} ${pad(p.validity ?? '', 10)}`); if (rows.length < list.length) line(C.dim(` … ${list.length - rows.length} lagi (pakai --semua)`)); out({ ok: true, category: catid, total: list.length, packages: rows }); } async function doPromo() { const c = needSession(); const list = await c.promotions(); if (!list.length) { line(C.yellow('Tidak ada penawaran personal saat ini.')); return out({ ok: true, deals: [] }); } line(C.bold(`Penawaran khusus ${localMsisdn(c.msisdn)} — ${list.length}`)); for (const p of list) { line(` ${pad(p.pvrCode, 9)} ${pad(p.name, 28)} ${pad(rupiah(p.price), 11)} ${pad(p.validity ?? '', 9)} ${C.dim(p.jenis)}`); } line(C.dim('\nBeli: bima beli contoh: bima beli 2146583')); out({ ok: true, deals: list }); } async function doAbout() { const W = 52; const vlen = (t) => String(t).replace(/\x1b\[[0-9;]*m/g, '').length; const row = (l, r = '') => `${BOX.v} ${l}${' '.repeat(Math.max(1, W - 2 - vlen(l) - vlen(r)))}${r} ${BOX.v}`; const sep = (t) => `${PLAIN ? '+' : '├'}${BOX.h} ${t} ${BOX.h.repeat(Math.max(1, W - t.length - 4))}${PLAIN ? '+' : '┤'}`; const top = `${BOX.tl}${BOX.h} ${BRAND.name} ${BOX.h.repeat(Math.max(1, W - BRAND.name.length - 4))}${BOX.tr}`; const fit = (t, maks = W - 6) => { const str = String(t); if (vlen(str) <= maks) return str; const potong = str.slice(0, Math.max(8, maks - 1)); return potong.slice(0, Math.floor(potong.length / 2)) + '…' + potong.slice(-Math.floor(potong.length / 2)); }; line(top); line(row('Versi', BRAND.version)); line(row('Lisensi', 'MIT (bebas dipakai & diubah)')); line(row('Author', BRAND.author)); line(row('GitHub', BRAND.github ? BRAND.github.replace(/^https?:\/\//, '') : '— belum diisi')); line(row('WhatsApp', BRAND.waChannel ? fit(BRAND.waChannel.replace(/^https?:\/\//, ''), W - 2 - 'WhatsApp'.length - 2) : '— belum diisi')); line(row('Telegram ch', BRAND.telegram ? fit(BRAND.telegram.replace(/^https?:\/\//, ''), W - 2 - 'Telegram ch'.length - 2) : '— belum diisi')); line(row('Telegram', BRAND.telegramPersonal ? fit(BRAND.telegramPersonal.replace(/^https?:\/\//, ''), W - 2 - 'Telegram'.length - 2) : '— belum diisi')); line(sep('Modul')); line(row('bima', 'Tri / IOH')); line(row('tsel', 'aktif · Telkomsel')); line(sep('Sumber & referensi')); for (const [nama, url] of BRAND.refs) { const u = url.replace(/^https?:\/\//, ''); const tampil = u.length > W - 8 ? u.slice(0, W - 9) + '…' : u; line(row(`• ${nama}`, '')); line(row(` ${tampil}`, '')); } line(`${BOX.bl}${BOX.h.repeat(W - 1)}${BOX.br}`); line(C.dim(' Salin link lengkap: nyx links')); out({ ok: true, brand: BRAND }); } async function doLinks() { const rows = [ ['WhatsApp channel', BRAND.waChannel], ['Telegram channel', BRAND.telegram], ['Telegram (kontak)', BRAND.telegramPersonal], ['GitHub', BRAND.github], ]; for (const [label, url] of rows) { if (!url) continue; line(C.bold(label)); line(' ' + C.cyan(url)); } out({ ok: true, links: Object.fromEntries(rows.filter(([, u]) => u)) }); } async function doKategori(force = false) { const c = needSession(); const rows = force ? await c.categoryCounts({ force: true }) : await c.categoryCounts(); const ada = rows.filter((r) => r.count > 0); let last = ''; line(C.bold(`Kategori — ${ada.length} berisi paket dari ${rows.length} subkategori`)); for (const r of ada) { if (r.parent !== last) { line(C.dim('· ' + r.parent)); last = r.parent; } line(` ${pad(r.id, 9)} ${pad(r.title, 26)} ${String(r.count).padStart(3)} paket`); } line(C.dim('\nContoh: bima paket 281 (ISTIMEWA) · bima paket 2453 (Happy 5G) · bima paket 2383 (Happy Harian)')); line(C.dim('Pakai --refresh untuk hitung ulang (cache 24 jam).')); out({ ok: true, categories: rows }); } async function doDetail(code) { if (!code) return fail(new Error('Kode paket wajib: detail ')); const c = needSession(); const j = await c.detail(code); const p = j.data?.commercial_package; if (!p) return fail(new Error('Paket tidak ditemukan.')); const ch = await c.channels(p.paymentchannels || p.commercial_attribute?.payment_methods || 'BALANCE,QRIS').catch(() => null); line(C.bold(p.package_name)); line(` Kode : ${p.pvr_code}`); line(` Harga : ${rupiah(p.tariff)}${Number(p.original_tariff) > Number(p.tariff) ? C.dim(' (normal ' + rupiah(p.original_tariff) + ')') : ''}`); line(` Masa aktif: ${p.commercial_attribute?.duration_month ?? '-'}`); line(` Keyword : ${C.dim(p.keyword ?? '-')}`); if (p.package_footer_desc) line(` Benefit : ${p.package_footer_desc}`); if (ch) line(` Channel : ${channelsOf(ch.data).map((x) => x.id).join(', ')}`); out({ ok: true, package: p, channels: ch ? channelsOf(ch.data) : [] }); } /* ------------------------------------------------------------------ beli */ async function doBeli(code, channel = 'QRIS') { if (!code) return fail(new Error('Kode paket wajib: beli ')); const c = needSession(); const j = await c.detail(code); const p = j.data?.commercial_package; if (!p) return fail(new Error('Paket tidak ditemukan.')); const validity = String(p.commercial_attribute?.duration_month ?? '1').match(/\d+/)?.[0] ?? '1'; const payload = { pvrCode: p.pvr_code, keyword: p.keyword ?? '', packageName: p.package_name, price: p.tariff, validity, channel }; if (dryRun) { line(C.yellow('DRY RUN — tidak ada request dikirim.')); line(JSON.stringify(payload, null, 2)); return out({ ok: true, dryRun: true, payload }); } if (curlOut) { const body = c.qrisBody(payload); line(C.bold('# Setara dengan perintah curl berikut:')); line(c.buildCurl(ENDPOINTS.initiatePayment, body)); return out({ ok: true, curl: c.buildCurl(ENDPOINTS.initiatePayment, body) }); } line(C.dim(`Membuat tagihan ${channel} untuk ${p.package_name} — ${rupiah(p.tariff)} ...`)); const order = await c.buyQris(payload); line(C.green('✓ Tagihan dibuat')); line(` Produk : ${p.package_name}`); line(` Nominal : ${rupiah(order.amount?.replace?.(/[^\d]/g, '') ?? p.tariff)}`); line(` Transid : ${order.transid}`); line(` Kadaluarsa: ${order.expiryMinutes} menit`); line(` CRC QRIS : ${order.crcValid ? C.green('valid') : C.red('TIDAK VALID')}`); line(''); line(C.bold('QR (buka di HP, screenshot, bayar dari galeri):')); line(' ' + C.cyan(order.imageUrl)); line(''); line(C.bold('Payload QRIS:')); line(' ' + C.dim(order.payload)); out({ ok: true, order }); } async function doQris() { const c = needSession(); const list = await c.pendingQrisOrders(); if (!list.length) { line('Tidak ada tagihan QRIS yang pending.'); return out({ ok: true, orders: [] }); } line(C.bold(`Tagihan QRIS pending (${list.length})`)); for (const o of list) { line(` • ${pad(o.product ?? '-', 24)} ${pad(rupiah(o.amount), 12)} ${C.dim(o.createdAt ?? '')} (${o.expiryMinutes} mnt)`); line(' ' + C.cyan(o.imageUrl)); } out({ ok: true, orders: list }); } async function doDarurat() { const c = needSession(); const j = await c.emgList(); const list = j.data?.servicelist ?? (j.data?.serviceList ?? []); line(C.bold('Paket Darurat (SOS) — dipakai saat pulsa kurang, biaya ditagih menyusul')); list.forEach((s, i) => { const ok = /eligible/i.test(String(s.sos?.eligible)) || String(s.sos?.eligibilitystatus).toUpperCase() === 'ELIGIBLE'; line(` ${i + 1}. ${pad(s.name, 34)} ${pad(rupiah(s.price), 11)} ${ok ? C.green('eligible') : C.dim('tidak eligible')} ${C.dim('kode ' + s.actioncode)}`); }); out({ ok: true, services: list }); } async function doDaruratBeli(sel) { if (!sel) return fail(new Error('Pilih paket: darurat-beli ')); const c = needSession(); const j = await c.emgList(); const list = j.data?.servicelist ?? (j.data?.serviceList ?? []); const pick = /^\d+$/.test(sel) ? list[Number(sel) - 1] : list.find((s) => s.actioncode === sel || s.param === sel); if (!pick) return fail(new Error('Paket darurat tidak ditemukan. Lihat `darurat`.')); if (dryRun) { line(C.yellow('DRY RUN — tidak ada request dikirim.')); return out({ ok: true, dryRun: true, pick }); } const r = await c.activateEmergency({ actioncode: pick.actioncode, name: pick.name, price: pick.price, amount: pick.sos?.amount, fee: pick.sos?.fee, period: pick.sos?.period, periodUnit: pick.sos?.periodunit, }); const ok = String(r.status) === '0'; line(ok ? C.green('✓ Paket darurat diaktifkan: ' + pick.name) : C.yellow('Respons: ' + (r.message ?? ''))); line(C.dim(' Cek kuota dengan: node cli.mjs status')); out({ ok, response: r }); } async function doApi(endpoint, jsonText) { if (!endpoint) return fail(new Error('Perlu endpoint: api \'{...}\'')); let body = {}; if (jsonText) { try { body = JSON.parse(jsonText); } catch { return fail(new Error('Body bukan JSON valid.')); } } const c = needSession(); if (curlOut) { const cmd = c.buildCurl(endpoint, body); line(cmd); return out({ ok: true, curl: cmd }); } const j = await c.post(endpoint, body); line(JSON.stringify(j, null, 2)); out({ ok: true, response: j }); } const UI_CTX = { C, pad, rupiah, localMsisdn, BimaClient, loadSession, saveSession, balanceOf, activePackagesOf, quotasOf, catalogOf, rewardsOf, ENDPOINTS, statusCard, BRAND, creditLine, PLAIN, tsel: { hasSession: () => { try { return fs.existsSync(TSEL_SESSION_PATH); } catch { return false; } }, login: tselLogin, verify: tselVerify, status: tselStatus, paket: tselPaket, beli: tselBeli, info: tselInfo, voucher: tselVoucher, riwayat: tselRiwayat, poin: tselPoin, reward: tselReward, profil: tselProfil, game: tselGame, logout: () => { try { fs.unlinkSync(TSEL_SESSION_PATH); } catch {} }, }, }; /** Kartu ringkasan akun — dipakai `bima status` dan menu 1. */ async function statusCard(c) { const d = (await c.dashboard()).data ?? {}; const info = d.prepaidinfo ?? {}; const sd = summaryOf(d); const pkgs = activePackageDetails(d); let poin = null; try { poin = (await c.points()).data ?? null; } catch {} const W = 52; const top = (t) => `${BOX.tl}${BOX.h} ${t} ${BOX.h.repeat(Math.max(1, W - t.length - 4))}${BOX.tr}`; const sep = (t) => `${PLAIN ? '+' : '├'}${BOX.h} ${t} ${BOX.h.repeat(Math.max(1, W - t.length - 4))}${PLAIN ? '+' : '┤'}`; const vlen = (t) => String(t).replace(/\x1b\[[0-9;]*m/g, '').length; const row = (left, right = '') => { const pad2 = Math.max(1, W - 2 - vlen(left) - vlen(right)); return `${BOX.v} ${left}${' '.repeat(pad2)}${right} ${BOX.v}`; }; const bot = `${BOX.bl}${BOX.h.repeat(W - 1)}${BOX.br}`; line(top(localMsisdn(c.msisdn))); line(row('Tri · PREPAID', `${pkgs.length} paket aktif`)); line(row('Masa aktif', info.cardactiveuntil ?? '-')); if (info.graceperioduntil) line(row('Masa tenggang', info.graceperioduntil)); line(row(C.bold('Pulsa'), rupiah(balanceOf(d)))); const ci = d.customerinfo ?? {}; line(row('SIM', `${ci.sim4G ? '4G/5G' : 'belum 4G'}${ci.upgradeeligible ? ' · siap upgrade' : ''}`)); if (poin) line(row('BonsTri', `${poin.redeemablepoints ?? 0} poin · ${poin.tierlevel ?? '-'} · exp ${poin.expireson ?? '-'}`)); line(sep('Kuota')); line(row('Sisa total', `${fmtKB(sd.remaining)} dari ${fmtKB(sd.initial)}`)); line(row('Terpakai', fmtKB(sd.used))); if (pkgs.length) { line(sep('Rincian paket')); for (const p of pkgs) { line(row(`• ${p.name}`, `s.d. ${p.end}`)); for (const q of p.quotas) { if (q.monetary) continue; const sisa = q.initial ? `${fmtBytes(q.remaining)} / ${fmtBytes(q.initial)}` : fmtBytes(q.remaining); line(row(` ${q.name}`, sisa)); } } } const alerts = (d.smartAlerts ?? []).map((a) => String(a.title ?? '').replace(//gi, ' ').replace(/<[^>]+>/g, '').replace(/&/g, '&').replace(/\s+/g, ' ').trim()).filter(Boolean); if (alerts.length) { line(sep('Pemberitahuan')); for (const a of alerts.slice(0, 4)) { const wrapped = a.match(new RegExp(`.{1,${W - 6}}(\\s|$)|.+$`, 'g')) ?? [a]; for (const [i, chunk] of wrapped.entries()) line(row((i ? ' ' : '• ') + chunk.trim())); } } const ec = d.emergencyCredit?.ecDetails; if (ec && Number(ec.dueamount ?? 0) > 0) { line(sep('Catatan')); line(row('⚠ Layanan Darurat', 'belum dilunasi')); line(row(' terpakai', `2 GB + fee (${ec.validitymsg ?? ''})`.trim())); } line(bot); return { msisdn: c.msisdn, pulsa: balanceOf(d), kuota: sd, paket: pkgs, poin }; } /* --------------------------------------------------------- modul tsel */ const TSEL_PENDING = TSEL_SESSION_PATH.replace('tsel-session.json', 'tsel-pending.json'); function tselNeedSession() { const s = loadTselSession(); if (!s?.accessToken) { console.error(C.red('Belum login (tsel).') + ' Jalankan: ' + C.bold('nyx tsel login 08xxxxxxxxxx')); process.exit(2); } return MyTelkomselClient.fromSession(s); } async function tselLogin(number) { if (!number) return fail(new Error('Nomor wajib: nyx tsel login 08xxxxxxxxxx')); const c = new MyTelkomselClient({ msisdn: number }); line(C.dim('Meminta OTP ke CIAM Telkomsel…')); let r; try { r = await c.requestOtp(); } catch (e) { const d = String(e.details ?? '').replace(/\s+/g, ' ').slice(0, 200); return fail(Object.assign(new Error(`OTP gagal (HTTP ${e.status})`), { code: e.code, details: d })); } fs.writeFileSync(TSEL_PENDING, JSON.stringify({ msisdn: c.msisdn, authId: r.authId, cookies: c.cookies, xDevice: c.xDevice }, null, 2), { mode: 0o600 }); line(C.green('✓ OTP dikirim ke ') + localMsisdn(c.msisdn)); line(C.dim('Lanjut: ') + C.bold('nyx tsel verify ')); out({ ok: true, msisdn: c.msisdn, authId: r.authId }); } async function tselVerify(otp) { if (!otp) return fail(new Error('Kode OTP wajib: nyx tsel verify 123456')); let p; try { p = JSON.parse(fs.readFileSync(TSEL_PENDING, 'utf8')); } catch { return fail(new Error('Belum minta OTP. Jalankan: nyx tsel login ')); } const c = new MyTelkomselClient({ msisdn: p.msisdn, cookies: p.cookies ?? {}, xDevice: p.xDevice }); c.authId = p.authId; const t = await c.submitOtp(otp); const where = saveTselSession(c.session()); try { fs.unlinkSync(TSEL_PENDING); } catch {} line(C.green('✓ Login Telkomsel berhasil') + C.dim(' sesi: ' + where)); line(C.dim('access_token: ') + String(t.accessToken).slice(0, 12) + '…'); out({ ok: true, msisdn: c.msisdn, expiresIn: t.expiresIn }); } async function tselStatus() { const c = tselNeedSession(); const d = await c.dashboard(); const bal = d.balance ?? {}; let loy = d.loyalty?.profiles ?? {}; // dashboard() memanggil 4 endpoint paralel; kadang loyalty balik kosong (rate limit). if (!Number(loy.loyalty_points ?? 0)) { try { loy = (await c.loyalty()).data?.profiles ?? loy; } catch {} } const quotas = quotaListOf(d.quota ?? {}); const tgl = (iso) => { if (!iso) return '-'; const [y, m, dd] = String(iso).split('-'); const bulan = ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Agu','Sep','Okt','Nov','Des']; return dd && m ? `${Number(dd)} ${bulan[Number(m) - 1]} ${y}` : iso; }; const W = 50; const vlen = (t) => String(t).replace(/\x1b\[[0-9;]*m/g, '').length; const row = (l, r = '') => `${BOX.v} ${l}${' '.repeat(Math.max(1, W - 2 - vlen(l) - vlen(r)))}${r} ${BOX.v}`; const top = `${BOX.tl}${BOX.h} Telkomsel · ${localMsisdn(c.msisdn)} ${BOX.h.repeat(Math.max(1, W - 26))}${BOX.tr}`; const sep = (t) => `${PLAIN ? '+' : '├'}${BOX.h} ${t} ${BOX.h.repeat(Math.max(1, W - t.length - 4))}${PLAIN ? '+' : '┤'}`; const bot = `${BOX.bl}${BOX.h.repeat(W - 1)}${BOX.br}`; line(top); line(row('Pulsa', rupiah(Number(bal.balance ?? 0)))); line(row('Masa aktif', tgl(bal.expiry_date))); if (loy.loyalty_points) line(row('Telkomsel Poin', `${loy.loyalty_points} · ${loy.loyalty_points_category ?? '-'}`)); if (quotas.length) { line(sep('Kuota')); for (const g of quotas) { line(row(g.class, g.total ?? '-')); for (const it of g.items) line(row(' ' + it.name, `${it.remaining} · ${tgl(it.expiry)}`)); } } line(bot); line(C.dim(' Paket tersedia: nyx tsel paket')); out({ ok: true, msisdn: c.msisdn, balance: bal, loyalty: loy, quota: quotas }); } async function tselPaket() { const c = tselNeedSession(); const list = await c.packages(); line(C.bold(`Paket tersedia — ${list.length}`)); for (const o of list.slice(0, 30)) { line(` ${pad(o.id, 12)} ${pad(o.name ?? '-', 30)} ${pad(rupiah(Number(o.price ?? 0)), 12)} ${pad(o.validity ?? '', 10)} ${C.dim(o.category ?? '')}`); } out({ ok: true, offers: list }); } async function tselDetail(id) { if (!id) return fail(new Error('Perlu id paket: nyx tsel detail ')); const c = tselNeedSession(); const d = await c.packageDetail(id); line(JSON.stringify(d, null, 2).slice(0, 2000)); out({ ok: true, detail: d }); } async function tselBeli(id, method = 'qris') { if (!id) return fail(new Error('Perlu id paket: nyx tsel beli ')); const c = tselNeedSession(); const d = await c.packageDetail(id).catch(() => null); const harga = d?.offer?.price ? Number(d.offer.price) : null; if (dryRun) { line(C.yellow('DRY RUN — tidak ada request dikirim.')); line(JSON.stringify({ offerId: id, paymentMethod: method, harga }, null, 2)); return out({ ok: true, dryRun: true, offerId: id, method }); } line(C.dim(`Membuat tagihan ${String(method).toUpperCase()}${harga ? ' — ' + rupiah(harga) : ''} …`)); let r; try { r = await c.buy({ offerId: id, paymentMethod: method }); } catch (e) { return fail(Object.assign(new Error('Pembelian ditolak'), { code: e.code, details: String(e.details ?? e.message).slice(0, 300) })); } const x = r.data ?? {}; const ok = String(x.reasoncode ?? '') === '00' || String(x.transactionstatus ?? '') === '00'; const menit = Math.round(Number(x.countDown ?? 0) / 60); line(ok ? C.green('✓ Tagihan dibuat') : C.yellow('Respons: ' + (x.transactiondesc ?? x.reason ?? '-'))); if (x.orderid) line(` Order ID : ${x.orderid}`); if (x.qrURL) { line(` Berlaku : ${menit} menit`); line(` Admin fee : ${rupiah(Number(x.adminFee ?? 0))}`); line(''); line(C.bold('QR (buka di HP, lalu bayar dari aplikasi e-wallet / m-banking):')); line(' ' + C.cyan(x.qrURL)); } line(''); line(C.dim('Setelah dibayar, cek paket aktif: nyx tsel status')); out({ ok, order: x }); } async function tselInfo() { const c = tselNeedSession(); const d = await c.info(); const tier = d.profile_tier ?? '-'; const los = Number(d.profile_los ?? 0); const arpu = Number(d.profile_arpu ?? 0); const W = 44; const vlen = (t) => String(t).replace(/\x1b\[[0-9;]*m/g, '').length; const row = (l) => `${BOX.v} ${l}${' '.repeat(Math.max(1, W - 2 - vlen(l)))} ${BOX.v}`; const judul = `Pelanggan · ${localMsisdn(c.msisdn)}`; line(`${BOX.tl}${BOX.h} ${judul} ${BOX.h.repeat(Math.max(1, W - judul.length - 3))}${BOX.tr}`); line(row('Tier ' + tier)); line(row('LOS ' + los + ' hari sejak aktivasi')); line(row('ARPU ' + rupiah(arpu) + ' / bulan')); line(`${BOX.bl}${BOX.h.repeat(W - 1)}${BOX.br}`); out({ ok: true, msisdn: c.msisdn, tier, los, arpu }); } async function tselVoucher() { const c = tselNeedSession(); const list = await c.vouchers(); line(C.bold(`Voucher fisik (${list.length})`) + C.dim(' harga jual gerai')); list.forEach((v) => line(` ${pad(String(v.id), 3)} ${pad(v.name, 20)} ${pad(rupiah(v.cost), 11)} ${pad(String(v.validity ?? '') + ' hari', 9)} ${C.dim(v.points + ' poin')}`)); line(C.dim(' Beli lewat aplikasi MyTelkomsel atau gerai.')); out({ ok: true, vouchers: list }); } async function tselPoin() { const c = tselNeedSession(); const [loy, h] = await Promise.all([c.loyalty(), c.pointHistory(1)]); const p = loy.data?.profiles ?? {}; line(C.bold(`Telkomsel Poin ${p.loyalty_points ?? 0}`) + C.dim(` · tier ${p.loyalty_points_category ?? '-'}`)); if (h.poinExpireDate && /\\d/.test(String(h.poinExpireDate))) line(C.dim(` hangus: ${h.poinExpireDate}`)); const rows = []; for (const bulan of (h.list ?? [])) for (const e of (bulan.data ?? [])) rows.push(e); if (!rows.length) { line(C.dim(' Belum ada mutasi poin.')); return out({ ok: true, poin: p.loyalty_points ?? 0, riwayat: [] }); } line(''); for (const e of rows.slice(0, 10)) { const v = String(e.value_poin ?? ''); line(` ${pad(e.transaction_date ?? '', 18)} ${pad(e.transaction_desc ?? '-', 26)} ${(v.startsWith('+') ? C.green(v) : C.red(v))}`); } out({ ok: true, poin: p.loyalty_points ?? 0, hangus: h.poinExpireDate, riwayat: rows }); } async function tselProfil() { const c = tselNeedSession(); const d = await c.profileFull(); const p = d.profiles ?? {}; const puk = flagValue('--puk') ? `${p.puk1 ?? '-'} / ${p.puk2 ?? '-'}` : '••••••••'; const W = 46; const vlen = (t) => String(t).replace(/\x1b\[[0-9;]*m/g, '').length; const row = (l) => `${BOX.v} ${l}${' '.repeat(Math.max(1, W - 2 - vlen(l)))} ${BOX.v}`; const judul = `Profil · ${localMsisdn(c.msisdn)}`; line(`${BOX.tl}${BOX.h} ${judul} ${BOX.h.repeat(Math.max(1, W - judul.length - 3))}${BOX.tr}`); line(row('Brand ' + (p.brand ?? '-'))); line(row('Paket ' + String(p.priceplan ?? '-').slice(0, 30))); line(row('Tipe ' + (p.isPrepaid ? 'prabayar' : p.isPostpaid ? 'pascabayar' : '-'))); line(row('Masa aktif ' + (p.gracedate ?? '-'))); line(row('Berakhir ' + (p.cancel_date ?? '-'))); line(row('PUK ' + puk)); line(`${BOX.bl}${BOX.h.repeat(W - 1)}${BOX.br}`); if (!flagValue('--puk')) line(C.dim(' PUK disamarkan — tampilkan dengan: nyx tsel profil --puk')); out({ ok: true, msisdn: c.msisdn, ...p }); } async function tselGame() { const c = tselNeedSession(); const list = await c.games(); const kata = String(flagValue('--cari') || '').toLowerCase(); const hasil = kata ? list.filter((g) => String(g.name).toLowerCase().includes(kata)) : list; line(C.bold(`Voucher game (${hasil.length}/${list.length})`) + C.dim(' harga mulai')); for (const g of hasil.slice(0, 20)) { line(` ${pad(String(g.name).slice(0, 28), 29)} ${pad(g.price ? rupiah(g.price) : '-', 11)} ${C.dim(String(g.ref ?? '').slice(0, 12))}`); } if (hasil.length > 20) line(C.dim(` … ${hasil.length - 20} lagi, persempit: --cari `)); out({ ok: true, games: hasil }); } async function tselReward(halaman = 1, kata = '') { const c = tselNeedSession(); const maks = flagValue('--maks') ? Number(flagValue('--maks')) : null; const kat = flagValue('--kategori') || ''; const angka = (n) => Number(n ?? 0).toLocaleString('id-ID'); let r = await c.rewards(halaman, kat); let list = r.list; let jejak = `hal ${r.page}/${r.pageCount}`; if (kata) list = list.filter((x) => String(x.title ?? '').toLowerCase().includes(kata.toLowerCase())); // --maks: sisir beberapa halaman karena API mengurutkan dari poin terbesar if (maks) { const sapu = Math.max(1, Number(flagValue('--sisir') || 5)); const kumpul = list.filter((x) => Number(x.poin ?? 0) <= maks); for (let p = halaman + 1; p <= Math.min(r.pageCount, halaman + sapu - 1); p++) { const nx = await c.rewards(p, kat).catch(() => null); if (!nx) break; kumpul.push(...nx.list.filter((x) => Number(x.poin ?? 0) <= maks)); } list = kumpul.sort((a, b) => Number(a.poin ?? 0) - Number(b.poin ?? 0)).slice(0, 20); jejak = `${sapu} halaman disisir`; } line(C.bold('Katalog reward Telkomsel Poin') + C.dim(` ${jejak}${kat ? ' · ' + kat : ''}${maks ? ' · ≤ ' + angka(maks) + ' poin' : ''}`)); if (!list.length) { line(C.dim(' Tidak ada yang cocok.')); return out({ ok: true, rewards: [] }); } list.forEach((x, i) => { line(` ${String(i + 1).padStart(2)}. ${pad(String(x.title ?? '-').slice(0, 40), 41)} ${pad(angka(x.poin) + ' poin', 14)} ${C.dim(String(x.category ?? ''))}`); }); line(C.dim(' halaman lain: nyx tsel reward · filter: --maks N · --kategori ')); out({ ok: true, page: r.page, pageCount: r.pageCount, rewards: list }); } async function tselRiwayat() { const c = tselNeedSession(); const list = await c.history(); if (!list.length) { line(C.dim('Belum ada transaksi tercatat di server untuk nomor ini.')); return out({ ok: true, msisdn: c.msisdn, transactions: [] }); } line(C.bold(`Riwayat transaksi (${list.length})`)); for (const t of list) { const tgl = t.date ?? t.createdAt ?? t.transactionDate ?? t.datetime ?? ''; const nama = t.name ?? t.productname ?? t.productName ?? t.title ?? '-'; const nilai = Number(t.amount ?? t.price ?? t.total ?? 0); const status = String(t.status ?? t.transactionStatus ?? '-'); line(` ${pad(String(tgl).slice(0, 19), 20)} ${pad(nama, 24)} ${pad(rupiah(nilai), 11)} ${/fail|gagal/i.test(status) ? C.red(status) : C.green(status)}`); } out({ ok: true, msisdn: c.msisdn, transactions: list }); } async function tselMain(command, args) { switch (command) { case 'login': await tselLogin(args[0]); break; case 'verify': await tselVerify(args[0]); break; case 'status': await tselStatus(); break; case 'paket': await tselPaket(); break; case 'detail': await tselDetail(args[0]); break; case 'info': await tselInfo(); break; case 'voucher': await tselVoucher(); break; case 'poin': await tselPoin(); break; case 'reward': await tselReward(Number(args[0]) || 1, args[1] ?? ''); break; case 'profil': await tselProfil(); break; case 'game': await tselGame(); break; case 'riwayat': await tselRiwayat(); break; case 'beli': await tselBeli(args[0], args[1] || 'qris'); break; case 'logout': { try { fs.unlinkSync(TSEL_SESSION_PATH); } catch {} line('Sesi tsel dihapus.'); break; } case '': case 'menu': case 'help': line(C.bold('Modul tsel (Telkomsel)')); line(' nyx tsel login minta OTP'); line(' nyx tsel verify verifikasi & simpan sesi'); line(' nyx tsel status ringkasan akun'); line(' nyx tsel paket penawaran paket'); line(' nyx tsel detail detail satu paket'); line(' nyx tsel info tier, LOS, ARPU'); line(' nyx tsel voucher voucher fisik (13 nominal)'); line(' nyx tsel poin poin + mutasi terakhir'); line(' nyx tsel reward [hal] katalog reward poin --maks N --kategori X'); line(' nyx tsel profil brand, paket, masa aktif (--puk)'); line(' nyx tsel game voucher game --cari '); line(' nyx tsel riwayat riwayat transaksi'); line(' nyx tsel beli beli paket (qris)'); line(' nyx tsel logout hapus sesi'); break; default: fail(new Error('Perintah tsel tidak dikenal: ' + command)); } } /* ------------------------------------------------------------------ main */ try { if (isTsel) await tselMain(cmd, rest); else switch (cmd) { case 'login': await doLogin(rest[0]); break; case 'verify': await doVerify(rest[0]); break; case 'status': await doStatus(); break; case 'poin': await doPoints(); break; case 'reward': await doRewards(rest[0]); break; case 'notif': await doNotif(); break; case 'riwayat': await doHistory(); break; case 'paket': { const catArg = rest[0] ?? flagValue('--cat'); if (!catArg && !flags.has('--semua') && !flagValue('--maks') && !rest[1]) await doKategori(); else await doPaket(catArg ?? '31', rest[1] ?? flagValue('--cari') ?? '', flagValue('--maks'), flags.has('--semua')); break; } case 'promo': await doPromo(); break; case 'about': case 'tentang': await doAbout(); break; case 'links': case 'link': await doLinks(); break; case 'kategori': await doKategori(flags.has('--refresh')); break; case 'detail': await doDetail(rest[0]); break; case 'beli': await doBeli(rest[0], rest[1] || 'QRIS'); break; case 'qris': await doQris(); break; case 'darurat': await doDarurat(); break; case 'darurat-beli': await doDaruratBeli(rest[0]); break; case 'api': await doApi(rest[0], rest[1]); break; case 'help': case '-h': case '--help': help(); break; case '': case 'menu': case 'i': await runInteractive(UI_CTX); break; default: if (argv.length === 0) await runInteractive(UI_CTX); else help(); } } catch (err) { fail(err); }