npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

opex-lenta-api

v0.1.4

Published

Lenta.com wrappper to get bonus card

Readme

opex-lenta-api

A modern, promise-based Node.js library for interacting with the Lenta.com API. It provides a simple and flexible interface for authentication, data retrieval, and now includes proxy support.

Features

  • Modern Syntax: Written in ESM (ES Modules) with full support for async/await.
  • Flexible State Management: Stateless design—you control session storage (file, database, etc.).
  • Proxy Support: Easily configure proxy agents for all outgoing requests.
  • Automatic Cookie Handling: Manages cookies automatically across requests.
  • High-Level & Low-Level Methods: Use convenience methods like getAllUserData() or specific endpoints like getProfile().
  • Helper Utilities: Automatically generates barcode image links for bonus cards.
  • Multi-Account Support: Manage sessions for multiple users via separate API instances.

Installation

Requires https-proxy-agent:

npm install opex-lenta-api https-proxy-agent

Getting Started

Example: Log in and retrieve user data with proxy support. Sessions are stored in all_sessions.json.

import { LentaAPI } from 'opex-lenta-api';
import { HttpsProxyAgent } from 'https-proxy-agent';
import fs from 'fs';
import readline from 'readline/promises';

const SESSIONS_FILE = 'all_sessions.json';

// Helper functions to manage state
function loadAllSessions() {
    try {
        return JSON.parse(fs.readFileSync(SESSIONS_FILE, 'utf-8'));
    } catch {
        return {};
    }
}

function saveAllSessions(sessions) {
    fs.writeFileSync(SESSIONS_FILE, JSON.stringify(sessions, null, 2));
}

async function main() {
    const phone = process.argv[2];
    if (!phone) {
        console.log('Usage: node example.js <phone_number>');
        console.log('Set proxy via HTTPS_PROXY environment variable.');
        return;
    }
    
    // Check for proxy settings
    const proxyUrl = process.env.HTTPS_PROXY || process.env.https_proxy;
    let proxyAgent;
    if (proxyUrl) {
        console.log(`Using proxy: ${proxyUrl}`);
        proxyAgent = new HttpsProxyAgent(proxyUrl);
    }

    const allSessions = loadAllSessions();
    const initialState = allSessions[phone] || {};
    const api = new LentaAPI(initialState, { proxyAgent }); // Pass proxy agent

    if (!api.isLoggedIn()) {
        console.log(`Starting login for ${phone}...`);
        await api.requestLoginCode(phone);
        const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
        const code = await rl.question('Enter SMS code: ');
        rl.close();
        await api.completeLogin(phone, code);
        allSessions[phone] = api.getState();
        saveAllSessions(allSessions);
        console.log('Login successful! Session saved.');
    } else {
        console.log(`Already logged in as ${phone}.`);
    }

    console.log('\nFetching all user data...');
    const userData = await api.getAllUserData();
    console.log(JSON.stringify(userData, null, 2));
}

main().catch(console.error);

To Run:

First login (without proxy):

node example.js 79123456789

Subsequent runs (with proxy):

HTTPS_PROXY="http://user:[email protected]:8080" node example.js 79123456789

API Reference

new LentaAPI(initialState, options)

Creates a new API client instance.

Parameters:

  • initialState (Object, optional): Saved session state. Default: new session with new deviceId.
  • options (Object, optional):
    • proxyAgent (Object): Proxy agent instance (e.g., https-proxy-agent).

Examples:

// New session without proxy
const api_newUser = new LentaAPI();

// New session with proxy
const proxyAgent = new HttpsProxyAgent('http://user:pass@host:port');
const api_withProxy = new LentaAPI({}, { proxyAgent });

// Restore saved session
const savedState = { deviceId: "...", kfpKsid: "...", authToken: "...", passportId: "..." };
const api_existingUser = new LentaAPI(savedState);

State Management

api.getState()

Returns current session state for persistence.

Returns: Object

{
  "deviceId": "a1b2c3k4-e5f6-9263-abcd-ef0123459579",
  "kfpKsid": "f0e1d2c3-b4a5-4678-9532-3456789abcde",
  "authToken": "FINAL-TOKEN-A1B9G5D4E5F6G7H8I9KG31L2M3N4O5P6",
  "passportId": "92h28d84-6j44-4f14-b451-6928525c44c7"
}

api.isLoggedIn()

Checks if authenticated.
Returns: boolean


Authentication

async api.requestLoginCode(phone)

Initiates login by requesting SMS code.

  • phone (string): User phone (e.g., "79123456789").
    Returns: Promise<Object>

async api.completeLogin(phone, code)

Verifies SMS code and updates auth state.

  • phone (string): User phone.
  • code (string): 4-digit SMS code.
    Returns: Promise<Object>

Data Fetching (Requires Authentication)

async api.getProfile()

Retrieves primary user profile.
Returns: Promise<Object>

async api.getClientMe()

Retrieves extended client data (agreements, brand info).
Returns: Promise<Object>

async api.getBonusCards()

Retrieves bonus cards (auto-adds barcodeImageUrl).
Returns: Promise<Object>

async api.getAllUserData()

Fetches combined data from getProfile(), getClientMe(), and getBonusCards() in parallel.
Returns: Promise<Object>


Error Handling

Handle errors with try...catch:

try {
  const profile = await api.getProfile();
} catch (error) {
  console.error('Failed to get profile:', error.message);
  if (error.response) {
    console.error('Server response:', error.response.data);
  }
}