npm package: 2fa-adb-tools
Description: Capture 2FA verification codes from Android notifications for automated testing with Playwright
Author: pifpafi4
Latest version: 1.0.0

# 2FA ADB Tools

A Node.js library for automatically capturing 2FA verification codes from Android notifications using ADB and OCR, with seamless Playwright integration for end-to-end testing.

[![npm version](https://img.shields.io/npm/v/2fa-adb-tools.svg)](https://www.npmjs.com/package/2fa-adb-tools)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## 📋 Table of Contents

- [Features](#-features)
- [Installation](#-installation)
- [Prerequisites](#-prerequisites)
- [Quick Start](#-quick-start)
- [API Reference](#-api-reference)
- [Configuration](#-configuration)
- [Troubleshooting](#-troubleshooting)

## ✨ Features

- **Automatic 2FA Capture**: Monitors Android notifications and extracts verification codes using OCR
- **Playwright Integration**: Built-in helpers for seamless end-to-end testing
- **Customizable Gestures**: Configure swipe coordinates and intervals for notification dismissal
- **Smart Management**: Automatic screenshot cropping, cleanup, and storage with deduplication

## 📦 Installation

```bash
npm install 2fa-adb-tools
```

### Peer Dependency (for Playwright)

```bash
npm install --save-dev @playwright/test
```

## 🔧 Prerequisites

### Android Setup
1. Enable **USB Debugging** on your Android device
2. Install **ADB** (Android Debug Bridge)

#### Install ADB
- **Windows**: Download [Android Platform Tools](https://developer.android.com/studio/releases/platform-tools)
- **macOS**: `brew install android-platform-tools`
- **Linux**: `sudo apt-get install adb` (Debian/Ubuntu)

#### Verify Connection
```bash
adb devices
# Should show your device as "device"
```

## 🚀 Quick Start

### Standalone Usage

```javascript
const { TwoFAHelper } = require('2fa-adb-tools');

const helper = new TwoFAHelper({ screenshotInterval: 3000 });
await helper.startMonitoring();

try {
    const code = await helper.waitForCode(60000);
    console.log(`2FA code: ${code}`);
} finally {
    await helper.stopMonitoring();
}
```

### With Playwright

```javascript
const { test, expect } = require('@playwright/test');
const { TwoFAHelper, waitFor2FACode } = require('2fa-adb-tools');

test.describe('2FA Test', () => {
    let twoFAHelper;

    test.beforeAll(async () => {
        twoFAHelper = new TwoFAHelper({ screenshotInterval: 3000 });
        await twoFAHelper.startMonitoring();
    });

    test.afterAll(async () => {
        await twoFAHelper.stopMonitoring();
    });

    test('login with 2FA', async ({ page }) => {
        await page.goto('https://example.com/login');
        await page.fill('#username', process.env.USERNAME);
        await page.fill('#password', process.env.PASSWORD);
        await page.click('#submit');

        const code = await waitFor2FACode(page, twoFAHelper, {
            codeInputSelector: '#code-input',
            autoFill: true
        });

        await expect(page.locator('.success-message')).toBeVisible();
    });
});
```

## 📚 API Reference

### TwoFAHelper

Main class for Playwright integration and simplified 2FA code management.

| Method | Description |
|--------|-------------|
| `startMonitoring()` | Begin monitoring for 2FA codes |
| `stopMonitoring()` | Stop monitoring and cleanup |
| `waitForCode(timeout)` | Wait for next code (returns Promise<string>) |

### ADBMonitor

Low-level class for direct ADB interaction.

| Event | Description |
|-------|-------------|
| `code` | Emitted when a verification code is found |
| `error` | Emitted on errors |

### OCRProcessor

Handles text recognition from images.

```javascript
const ocr = new OCRProcessor({ languages: 'rus+eng' });
await ocr.init();
const text = await ocr.recognize('./screenshot.png');
const code = ocr.processText(text);
await ocr.terminate();
```

### ScreenshotManager

Manages screenshot capture and storage.

```javascript
const sm = new ScreenshotManager({
    adbPath: 'adb',
    deviceId: 'device-id',
    maxScreenshots: 50
});

const screenshot = await sm.takeScreenshot();
const cropped = await sm.cropScreenshot(screenshot);
sm.saveCodeScreenshot(screenshot, cropped, '123456');
```

## ⚙️ Configuration

### TwoFAHelper Options

```javascript
{
    // Monitoring
    screenshotInterval: 3000,      // How often to take screenshots (ms)
        autoSwipe: true,               // Enable/disable all swipes

        // Swipe behavior
        swipeAfterCode: true,          // Swipe after finding a code
        swipeInterval: 10000,          // Auto-swipe every 10 seconds (0 = disable)

        // Swipe coordinates
        swipeConfig: {
        startX: 150, startY: 1200,   // Start position
            endX: 950, endY: 1200,       // End position
            duration: 400                 // Swipe duration (ms)
    },

    // OCR crop region (where codes appear)
    cropConfig: {
        top: 930, bottom: 100,        // Vertical crop
            left: 100, right: 100         // Horizontal crop
    },

    // Advanced
    ocrLanguages: 'rus+eng',        // Tesseract languages
        deviceId: null,                  // Specific device ID
        maxScreenshots: 50               // Screenshots to keep
}
```

### Finding Coordinates

1. Enable **Pointer Location** in Developer Options on Android
2. Note the coordinates for your swipe gesture
3. Adjust `swipeConfig` accordingly

### Optimizing Crop Region

Adjust `cropConfig` to focus only on the area where 2FA codes appear in notifications.

## 🔍 Troubleshooting

| Issue | Solution |
|-------|----------|
| ADB not found | Install Android platform-tools and add to PATH |
| No devices | Run `adb devices`, enable USB debugging, re-authorize device |
| OCR fails | Adjust `cropConfig`, improve screenshot quality, check contrast |
| Swipe not working | Verify coordinates, increase duration, ensure screen is unlocked |

### Debug Mode

```javascript
// Enable verbose logging
process.env.DEBUG = '2fa-adb-tools:*';

// Log events
helper.on('code', console.log);
helper.on('error', console.error);
```

## 🤖 AI Disclosure

This project was developed with assistance from AI language models (DeepSeek) for code generation, documentation, and refactoring. The core logic, architecture decisions, and final code quality were reviewed, tested and approved by a human developer.

## 📄 License

MIT © [pifpafi4](https://github.com/pifpafi4) - делайте что хотите, я за код не отвечаю.