#!/usr/bin/env node /** * Perplexity (ai.perplexity.app.android) - Android API Client * Creator: SAURUS * Saluran: https://whatsapp.com/channel/0029VbDhTC6KLaHjHKXl552C * Note: pliss guys jangan di klaim 100% buatan lu, lu boleh kok modifikasi trs share lagi tapi tolong jangan ilangin header creator sama ch-nya */ import fs from 'node:fs'; import crypto from 'node:crypto'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; const SAURUS_META = { Creator: 'SAURUS', Saluran: 'https://whatsapp.com/channel/0029VbDhTC6KLaHjHKXl552C' }; const CONFIG = { BASE_URL: 'https://www.perplexity.ai', SUGGEST_URL: 'https://suggest.perplexity.ai', TEMPMAIL_URL: 'https://api.tempmail.ing/api', API_VERSION: '2.17', APP_VERSION: '2.105.0', USER_AGENT: 'Ask/2.105.0/260678 (Android; Version 9; OnePlus PJD110/PQ3B.190801.11101518 release-keys) SDK 28', SESSION_FILE: path.join(path.dirname(fileURLToPath(import.meta.url)), 'session.json'), TIMEOUT_MS: 60000 }; function generateDeviceId() { return crypto.randomBytes(8).toString('hex'); } function buildHeaders(jwt = null, deviceId = null, extra = {}) { const headers = { 'Accept-Encoding': 'gzip', 'Accept-Language': 'id-ID', 'User-Agent': CONFIG.USER_AGENT, 'X-App-ApiClient': 'android', 'X-App-ApiVersion': CONFIG.API_VERSION, 'X-App-Version': CONFIG.APP_VERSION, 'X-Client-Env': 'prod', 'X-Client-Name': 'Perplexity-Android', 'X-Client-Version': CONFIG.APP_VERSION, 'X-Device-ID': `android:${deviceId || generateDeviceId()}`, ...extra }; if (jwt) { headers['Authorization'] = `Bearer ${jwt}`; } return headers; } async function requestJson(url, options = {}) { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), CONFIG.TIMEOUT_MS); try { const res = await fetch(url, { ...options, signal: controller.signal }); const text = await res.text(); if (!res.ok) { throw new Error(`HTTP ${res.status}: ${text.slice(0, 300)}`); } return JSON.parse(text); } finally { clearTimeout(timer); } } async function generateTempEmail(durationMinutes = 10) { const res = await requestJson(`${CONFIG.TEMPMAIL_URL}/generate`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ duration: durationMinutes }) }); if (!res.success || !res.email?.address) { throw new Error('Failed to generate temporary email'); } return res.email.address; } async function getTempInbox(email) { return requestJson(`${CONFIG.TEMPMAIL_URL}/emails/${encodeURIComponent(email)}`, { method: 'GET' }); } async function sendOtp(email, deviceId = null) { const body = new URLSearchParams({ email, useNumericOtp: 'true' }).toString(); return requestJson(`${CONFIG.BASE_URL}/api/auth/signin-email`, { method: 'POST', headers: buildHeaders(null, deviceId, { 'Content-Type': 'application/x-www-form-urlencoded' }), body }); } async function verifyOtp(email, otp, deviceId = null) { return requestJson(`${CONFIG.BASE_URL}/api/auth/signin-otp`, { method: 'POST', headers: buildHeaders(null, deviceId, { 'Content-Type': 'application/json; charset=utf-8' }), body: JSON.stringify({ email, otp }) }); } async function refreshJwt(token, deviceId = null) { return requestJson(`${CONFIG.BASE_URL}/rest/auth/refresh_perplexity_jwt`, { method: 'GET', headers: buildHeaders(token, deviceId, { 'Content-Type': 'application/json' }) }); } async function getUser(jwt, deviceId = null) { return requestJson(`${CONFIG.BASE_URL}/api/user`, { method: 'GET', headers: buildHeaders(jwt, deviceId, { 'Content-Type': 'application/json' }) }); } async function getModels(jwt, deviceId = null) { return requestJson(`${CONFIG.BASE_URL}/rest/models/config/v2`, { method: 'GET', headers: buildHeaders(jwt, deviceId, { 'Content-Type': 'application/json' }) }); } async function getRateLimit(jwt, deviceId = null) { return requestJson(`${CONFIG.BASE_URL}/rest/rate-limit/status`, { method: 'GET', headers: buildHeaders(jwt, deviceId, { 'Content-Type': 'application/json' }) }); } async function suggest(q, jwt = null, deviceId = null) { const url = `${CONFIG.SUGGEST_URL}/suggest?q=${encodeURIComponent(q)}&version=${CONFIG.API_VERSION}&source=mobile`; return requestJson(url, { method: 'GET', headers: buildHeaders(jwt, deviceId, { 'Content-Type': 'application/json' }) }); } function loadSession() { if (!fs.existsSync(CONFIG.SESSION_FILE)) return null; try { return JSON.parse(fs.readFileSync(CONFIG.SESSION_FILE, 'utf8')); } catch { return null; } } function saveSession(session) { fs.writeFileSync(CONFIG.SESSION_FILE, JSON.stringify(session, null, 2), 'utf8'); return session; } async function createNewAccount() { const deviceId = generateDeviceId(); const email = await generateTempEmail(10); await sendOtp(email, deviceId); let otp = null; const deadline = Date.now() + 30000; while (Date.now() < deadline) { const inbox = await getTempInbox(email); const messages = inbox.messages || inbox.emails || inbox.data || []; for (const msg of messages) { const content = `${msg.subject || ''} ${msg.text || ''} ${msg.html || ''} ${msg.body || ''}`; const match = content.match(/\b(\d{6})\b/); if (match) { otp = match[1]; break; } } if (otp) break; await new Promise((r) => setTimeout(r, 2000)); } if (!otp) { throw new Error(`Timeout waiting for Perplexity OTP on ${email}`); } const auth = await verifyOtp(email, otp, deviceId); const jwtRes = await refreshJwt(auth.token, deviceId); const jwt = jwtRes.perplexity_jwt || auth.token; const user = await getUser(jwt, deviceId); const session = { email, jwt, user_nextauth_id: user.id || null, deviceId, frontend_context_uuid: crypto.randomUUID(), last_backend_uuid: null }; return saveSession(session); } function resetChatSession() { const session = loadSession(); if (!session) { throw new Error('No active account session. Run with --newaccount first.'); } session.frontend_context_uuid = crypto.randomUUID(); session.last_backend_uuid = null; return saveSession(session); } async function ask(query, options = {}) { let session = loadSession(); if (options.newAccount || !session || !session.jwt) { session = await createNewAccount(); } else if (options.newSession) { session.frontend_context_uuid = crypto.randomUUID(); session.last_backend_uuid = null; saveSession(session); } const jwt = options.jwt || session.jwt; const deviceId = session.deviceId || generateDeviceId(); const frontendContextUuid = session.frontend_context_uuid || crypto.randomUUID(); const params = { source: 'android', version: CONFIG.API_VERSION, frontend_uuid: crypto.randomUUID(), frontend_context_uuid: frontendContextUuid, android_device_id: deviceId, mode: options.mode || 'concise', model_preference: options.model || 'turbo', ...(options.params || {}) }; if (session.user_nextauth_id) { params.user_nextauth_id = session.user_nextauth_id; } if (session.last_backend_uuid) { params.last_backend_uuid = session.last_backend_uuid; } const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), CONFIG.TIMEOUT_MS); try { const res = await fetch(`${CONFIG.BASE_URL}/rest/sse/perplexity_ask`, { method: 'POST', headers: buildHeaders(jwt, deviceId, { 'Accept': 'text/event-stream', 'Content-Type': 'application/json; charset=utf-8' }), body: JSON.stringify({ query_str: query, params }), signal: controller.signal }); const raw = await res.text(); if (!res.ok) { throw new Error(`HTTP ${res.status}: ${raw.slice(0, 300)}`); } const events = []; for (const block of raw.split(/\r?\n\r?\n/)) { const dataLine = block.split(/\r?\n/).find((l) => l.startsWith('data:')); if (!dataLine) continue; const jsonStr = dataLine.slice(5).trim(); if (!jsonStr || jsonStr === '[DONE]') continue; try { events.push(JSON.parse(jsonStr)); } catch { } } let backendUuid = null; let answer = null; const images = new Set(); for (const ev of events) { if (ev.backend_uuid) backendUuid = ev.backend_uuid; if (ev.text) answer = ev.text; if (Array.isArray(ev.media_items)) { for (const item of ev.media_items) { if (item.url) images.add(item.url); if (item.image) images.add(item.image); } } if (Array.isArray(ev.blocks)) { for (const b of ev.blocks) { if (b.intended_usage === 'ask_text' && b.markdown_block?.answer) { answer = b.markdown_block.answer; } if (Array.isArray(b.media_block?.media_items)) { for (const item of b.media_block.media_items) { if (item.url) images.add(item.url); if (item.image) images.add(item.image); } } } } } if (backendUuid) { session.frontend_context_uuid = frontendContextUuid; session.last_backend_uuid = backendUuid; saveSession(session); } const result = { answer, backend_uuid: backendUuid, frontend_context_uuid: frontendContextUuid }; if (images.size > 0) { result.images = [...images]; } return result; } finally { clearTimeout(timer); } } function printSuccess(data) { console.log(JSON.stringify({ ...SAURUS_META, status: true, data }, null, 2)); } function printError(err) { console.error(JSON.stringify({ ...SAURUS_META, status: false, error: err instanceof Error ? err.message : String(err) }, null, 2)); process.exit(1); } async function main() { const args = process.argv.slice(2); const command = args[0]; if (!command || command === '--help' || command === '-h') { printSuccess({ description: 'Perplexity Android API Client (Auto-Gen Account & Session)', usage: { chat: 'node index.js "" [--newsession] [--newaccount]', newaccount: 'node index.js newaccount', newsession: 'node index.js newsession', suggest: 'node index.js suggest ""', user: 'node index.js user', models: 'node index.js models', limits: 'node index.js limits' } }); return; } try { const hasFlag = (flag) => args.includes(flag); const knownCommands = ['newaccount', 'newsession', 'suggest', 'user', 'models', 'limits', 'ask']; if (!knownCommands.includes(command)) { printSuccess(await ask(command, { newSession: hasFlag('--newsession'), newAccount: hasFlag('--newaccount') })); return; } if (command === 'newaccount') { const session = await createNewAccount(); printSuccess({ email: session.email, user_nextauth_id: session.user_nextauth_id, frontend_context_uuid: session.frontend_context_uuid }); } else if (command === 'newsession') { const session = resetChatSession(); printSuccess({ email: session.email, frontend_context_uuid: session.frontend_context_uuid, last_backend_uuid: session.last_backend_uuid }); } else if (command === 'ask') { if (!args[1]) throw new Error('Missing query'); printSuccess(await ask(args[1], { newSession: hasFlag('--newsession'), newAccount: hasFlag('--newaccount') })); } else if (command === 'suggest') { if (!args[1]) throw new Error('Missing query'); const session = loadSession(); printSuccess(await suggest(args[1], session?.jwt, session?.deviceId)); } else if (command === 'user') { const session = loadSession(); if (!session?.jwt) throw new Error('No active session. Run newaccount first.'); printSuccess(await getUser(session.jwt, session.deviceId)); } else if (command === 'models') { const session = loadSession(); if (!session?.jwt) throw new Error('No active session. Run newaccount first.'); printSuccess(await getModels(session.jwt, session.deviceId)); } else if (command === 'limits') { const session = loadSession(); if (!session?.jwt) throw new Error('No active session. Run newaccount first.'); printSuccess(await getRateLimit(session.jwt, session.deviceId)); } } catch (err) { printError(err); } } const currentFile = fileURLToPath(import.meta.url); if (process.argv[1] && path.resolve(process.argv[1]) === path.resolve(currentFile)) { main(); } export { SAURUS_META, CONFIG, generateDeviceId, generateTempEmail, getTempInbox, sendOtp, verifyOtp, refreshJwt, getUser, getModels, getRateLimit, suggest, createNewAccount, resetChatSession, ask }; export default { SAURUS_META, CONFIG, generateDeviceId, generateTempEmail, getTempInbox, sendOtp, verifyOtp, refreshJwt, getUser, getModels, getRateLimit, suggest, createNewAccount, resetChatSession, ask };