#!/usr/bin/env node // NYX PROJECT — modul tsel (Telkomsel / MyTelkomsel) · satu file // Author : Akwila Dimas · https://github.com/Akwds01 // Telegram: https://t.me/nyx_projectss · WhatsApp: https://whatsapp.com/channel/0029VbEMMAQHbFUzKKOE5o0Y // Sumber : web app my.telkomsel.com + APK MyTelkomsel 9.4.1 // License : MIT (2026, Akwila Dimas) — bebas dipakai/diubah/dibagikan dengan notice // Hasil build dari cli-tsel.mjs + lib/{tsel,brand}.mjs — modul bima TIDAK ikut di sini. import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import crypto from 'node:crypto'; import readline from 'node:readline/promises'; /* =========================== 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'); }; /* ============================ CLI ============================ */ // NYX PROJECT — modul tsel (Telkomsel / MyTelkomsel) · CLI mandiri // Author : Akwila Dimas · https://github.com/Akwds01 // Telegram: https://t.me/nyx_projectss · WhatsApp: https://whatsapp.com/channel/0029VbEMMAQHbFUzKKOE5o0Y // License : MIT (2026, Akwila Dimas) — bebas dipakai/diubah/dibagikan dengan notice // Berkas ini hanya berisi modul tsel. Modul bima (Tri/IOH) ada di cli.mjs terpisah. /* ------------------------------------------------------------- tampilan */ const rawArgs = process.argv.slice(2); const flags = new Set(rawArgs.filter((a) => a.startsWith('--'))); const VALUE_FLAGS = new Set(['--maks', '--kategori', '--sisir', '--cari']); const args = []; for (let i = 0; i < rawArgs.length; i++) { const a = rawArgs[i]; if (VALUE_FLAGS.has(a)) { i++; continue; } if (a.startsWith('--')) continue; args.push(a); } const flagValue = (name) => { const i = rawArgs.indexOf(name); return i >= 0 ? rawArgs[i + 1] : null; }; const cmd = (args[0] || '').toLowerCase(); const rest = args.slice(1); const asJson = flags.has('--json'); const dryRun = flags.has('--dry'); const PLAIN = process.env.NYX_PLAIN === '1' || process.env.NYX_ASCII === '1'; 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 line = (s = '') => { if (!asJson) console.log(s); }; const out = (obj) => { if (asJson) console.log(JSON.stringify(obj, null, 2)); }; const pad = (s, n) => String(s).padEnd(n).slice(0, n); const rupiah = (n) => 'Rp' + Number(n || 0).toLocaleString('id-ID'); const localNum = (v) => { const d = String(v ?? '').replace(/\D/g, ''); return d.startsWith('62') ? '0' + d.slice(2) : d.startsWith('0') ? d : '0' + d; }; const angka = (n) => Number(n ?? 0).toLocaleString('id-ID'); const vlen = (t) => String(t).replace(/\x1b\[[0-9;]*m/g, '').length; function fail(err) { const e = err instanceof Error ? err : new Error(String(err)); if (typeof e.details === 'string' && e.details) line(C.dim(' detail: ' + e.details.replace(/\s+/g, ' ').slice(0, 240))); console.error(C.red('✖ ' + e.message) + (e.code ? C.dim(' [' + e.code + ']') : '')); process.exit(1); } function needSession() { const s = loadTselSession(); if (!s?.accessToken) { console.error(C.red('Belum login.') + ' Jalankan: ' + C.bold('nyx-tsel login 08xxxxxxxxxx')); process.exit(2); } return MyTelkomselClient.fromSession(s); } /* ------------------------------------------------------------- perintah */ async function doLogin(nomor) { if (!nomor) return fail(new Error('Nomor wajib: login 08xxxxxxxxxx')); const c = new MyTelkomselClient({ msisdn: nomor }); 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 })); } const pending = TSEL_SESSION_PATH.replace('tsel-session.json', 'tsel-pending.json'); fs.writeFileSync(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 ') + localNum(c.msisdn)); line(C.dim('Lanjut: ') + C.bold('nyx-tsel verify ')); out({ ok: true, msisdn: c.msisdn }); } async function doVerify(otp) { if (!otp) return fail(new Error('Kode OTP wajib: verify 123456')); const pending = TSEL_SESSION_PATH.replace('tsel-session.json', 'tsel-pending.json'); let p; try { p = JSON.parse(fs.readFileSync(pending, 'utf8')); } catch { return fail(new Error('Belum minta OTP. Jalankan: 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(pending); } catch {} line(C.green('✓ Login Telkomsel berhasil') + C.dim(' sesi: ' + where)); out({ ok: true, msisdn: c.msisdn, expiresIn: t.expiresIn }); } async function doLogout() { try { fs.unlinkSync(TSEL_SESSION_PATH); line('Sesi tsel dihapus.'); } catch { line('Tidak ada sesi tersimpan.'); } } const tglId = (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; }; async function doStatus() { const c = needSession(); 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 W = 50; const row = (l, r = '') => BOX.v + ' ' + l + ' '.repeat(Math.max(1, W - 2 - vlen(l) - vlen(r))) + r + ' ' + BOX.v; const judul = 'Telkomsel · ' + localNum(c.msisdn); const sep = (t) => (PLAIN ? '+' : '├') + BOX.h + ' ' + t + ' ' + BOX.h.repeat(Math.max(1, W - t.length - 4)) + (PLAIN ? '+' : '┤'); line(BOX.tl + BOX.h + ' ' + judul + ' ' + BOX.h.repeat(Math.max(1, W - judul.length - 3)) + BOX.tr); line(row('Pulsa', rupiah(Number(bal.balance ?? 0)))); line(row('Masa aktif', tglId(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 + ' · ' + tglId(it.expiry))); } } line(BOX.bl + BOX.h.repeat(W - 1) + BOX.br); line(C.dim(' Paket tersedia: nyx-tsel paket')); out({ ok: true, msisdn: c.msisdn, balance: bal, loyalty: loy, quota: quotas }); } async function doPaket() { const c = needSession(); 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 doDetail(id) { if (!id) return fail(new Error('Perlu id paket: detail ')); const c = needSession(); const d = await c.packageDetail(id); line(JSON.stringify(d, null, 2).slice(0, 2000)); out({ ok: true, detail: d }); } async function doBeli(id, method = 'qris') { if (!id) return fail(new Error('Perlu id paket: beli ')); const c = needSession(); 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'; 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 : ' + Math.round(Number(x.countDown ?? 0) / 60) + ' 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 doInfo() { const c = needSession(); const d = await c.info(); const W = 44; const row = (l) => BOX.v + ' ' + l + ' '.repeat(Math.max(1, W - 2 - vlen(l))) + ' ' + BOX.v; const judul = 'Pelanggan · ' + localNum(c.msisdn); line(BOX.tl + BOX.h + ' ' + judul + ' ' + BOX.h.repeat(Math.max(1, W - judul.length - 3)) + BOX.tr); line(row('Tier ' + (d.profile_tier ?? '-'))); line(row('LOS ' + Number(d.profile_los ?? 0) + ' hari sejak aktivasi')); line(row('ARPU ' + rupiah(Number(d.profile_arpu ?? 0)) + ' / bulan')); line(BOX.bl + BOX.h.repeat(W - 1) + BOX.br); out({ ok: true, msisdn: c.msisdn, ...d }); } async function doProfil() { const c = needSession(); const d = await c.profileFull(); const p = d.profiles ?? {}; const puk = flagValue('--puk') ? (p.puk1 ?? '-') + ' / ' + (p.puk2 ?? '-') : '••••••••'; const W = 46; const row = (l) => BOX.v + ' ' + l + ' '.repeat(Math.max(1, W - 2 - vlen(l))) + ' ' + BOX.v; const judul = 'Profil · ' + localNum(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 doPoin() { const c = needSession(); 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, riwayat: rows }); } async function doReward(halaman = 1, kata = '') { const c = needSession(); const maks = flagValue('--maks') ? Number(flagValue('--maks')) : null; const kat = flagValue('--kategori') || ''; 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())); 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 doVoucher() { const c = needSession(); 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 doGame() { const c = needSession(); 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 doRiwayat() { const c = needSession(); 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 }); } const help = () => { line(C.bold('NYX TSEL — modul Telkomsel (satu file)')); line(C.dim(' ' + creditLine())); line(''); line(C.dim(' Jalankan tanpa argumen untuk menu interaktif.')); line(''); line(C.bold('Akun')); line(' login Kirim OTP (0812..., 62812..., +62812...)'); line(' verify Verifikasi OTP & simpan sesi'); line(' status Pulsa, masa aktif, poin, kuota'); line(' profil [--puk] Brand, paket, masa aktif, PUK'); line(' info Tier, LOS, ARPU'); line(' poin Telkomsel Poin + mutasi'); line(' logout Hapus sesi'); line(''); line(C.bold('Paket')); line(' paket Penawaran paket + harga'); line(' detail Detail satu paket'); line(' beli [qris] Buat tagihan QRIS'); line(''); line(C.bold('Reward & voucher')); line(' reward [hal] Katalog reward --maks N --kategori X --sisir N'); line(' voucher Voucher fisik (13 nominal)'); line(' game [--cari kata] Voucher game (75)'); line(''); line(C.bold('Opsi')); line(' --json Output JSON'); line(' --dry Tampilkan rencana tanpa mengirim (beli)'); line(''); line(C.dim(' Sesi: ' + TSEL_SESSION_PATH)); line(C.dim(' ' + BRAND.name + ' v' + BRAND.version + ' · ' + BRAND.tagline)); }; /* ------------------------------------------------------------- menu */ async function runMenu() { const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: process.stdin.isTTY }); class Exit extends Error {} 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 pause = async () => { await ask(C.dim('\n ↵ Enter untuk kembali ')); }; const ART = [ ' ███╗ ██╗██╗ ██╗██╗ ██╗', ' ████╗ ██║╚██╗ ██╔╝╚██╗██╔╝', ' ██╔██╗ ██║ ╚████╔╝ ╚███╔╝ ', ' ██║╚██╗██║ ╚██╔╝ ██╔██╗ ', ' ██║ ╚████║ ██║ ██╔╝ ██╗', ' ╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝', ].join('\n'); line(C.cyan(ART)); line(C.dim(' NYX PROJECT · modul tsel (Telkomsel)')); line(C.dim(' ' + creditLine())); line(C.dim(' detail: nyx-tsel help · sesi: ' + TSEL_SESSION_PATH)); line(C.dim(' ' + '─'.repeat(46))); if (!loadTselSession()?.accessToken) { line(''); line(' ' + C.bold('Masuk ke akun Telkomsel')); const nomor = (await ask(' Nomor (0812...): ')).trim(); if (!nomor) { line(C.dim('\n Sampai jumpa.\n')); rl.close(); return; } try { await doLogin(nomor); const otp = (await ask(' Kode OTP: ')).trim(); if (!otp) { line(C.dim('\n Sampai jumpa.\n')); rl.close(); return; } await doVerify(otp); } catch (e) { console.error(C.red(' ✖ ' + (e.message || e))); rl.close(); return; } } for (;;) { line(''); line(C.bold(' ── Menu tsel ──')); line(' 1. Ringkasan akun (pulsa, masa aktif, poin, kuota)'); line(' 2. Profil kartu (brand, masa aktif)'); line(' 3. Info pelanggan (tier, ARPU)'); line(' 4. Daftar paket'); line(' 5. Beli paket (QRIS)'); line(' 6. Telkomsel Poin & mutasi'); line(' 7. Katalog reward (tukar poin)'); line(' 8. Voucher fisik'); line(' 9. Voucher game'); line(' 10. Riwayat transaksi'); line(' 11. Login ulang / ganti nomor'); line(' 0. Keluar'); const pick = (await ask('\n Pilih: ')).trim(); try { if (pick === '1') { await doStatus(); await pause(); } else if (pick === '2') { await doProfil(); await pause(); } else if (pick === '3') { await doInfo(); await pause(); } else if (pick === '4') { await doPaket(); await pause(); } else if (pick === '5') { await doPaket(); const id = (await ask('\n ID paket (kosong = batal): ')).trim(); if (!id) { line(C.dim(' Dibatalkan.')); continue; } const yes = (await ask(' Buat tagihan QRIS? (y/N): ')).trim().toLowerCase(); if (yes === 'y') await doBeli(id, 'qris'); else line(C.dim(' Dibatalkan.')); await pause(); } else if (pick === '6') { await doPoin(); await pause(); } else if (pick === '7') { await doReward(1, ''); await pause(); } else if (pick === '8') { await doVoucher(); await pause(); } else if (pick === '9') { await doGame(); await pause(); } else if (pick === '10') { await doRiwayat(); await pause(); } else if (pick === '11') { line(''); const nomor = (await ask(' Nomor (0812...): ')).trim(); if (!nomor) continue; try { await doLogin(nomor); const otp = (await ask(' Kode OTP: ')).trim(); if (otp) await doVerify(otp); } catch (e) { console.error(C.red(' ✖ ' + (e.message || e))); } } else if (pick === '0' || pick === '') break; else line(C.dim(' Pilihan tidak dikenal.')); } catch (e) { if (e instanceof Exit) break; console.error(C.red('\n ✖ ' + (e.message || String(e))) + (e.code ? C.dim(' [' + e.code + ']') : '')); } } line('\n ' + C.dim('Sampai jumpa.') + '\n'); rl.close(); } /* ------------------------------------------------------------- main */ try { switch (cmd) { case 'login': await doLogin(rest[0]); break; case 'verify': await doVerify(rest[0]); break; case 'status': await doStatus(); break; case 'profil': await doProfil(); break; case 'info': await doInfo(); break; case 'poin': await doPoin(); break; case 'paket': await doPaket(); break; case 'detail': await doDetail(rest[0]); break; case 'beli': await doBeli(rest[0], rest[1] || 'qris'); break; case 'reward': await doReward(Number(rest[0]) || 1, rest[1] ?? ''); break; case 'voucher': await doVoucher(); break; case 'game': await doGame(); break; case 'riwayat': await doRiwayat(); break; case 'logout': await doLogout(); break; case 'about': case 'tentang': case 'help': case '-h': case '--help': help(); break; case '': case 'menu': case 'i': await runMenu(); break; default: help(); } } catch (err) { fail(err); }