npm package: @mrsadriddin/authenticator
Description: Telegram Single Sign-On (SSO) Client SDK for Node.js
Author: MrSadriddin
Latest version: 2.0.0

# @mrsadriddin/authenticator

> Telegram SSO uchun Node.js Client SDK. Zero dependency. Production-ready.

---

## Mundarija

- [O'rnatish](#ornatish)
- [Tezkor boshlash](#tezkor-boshlash)
- [Konstruktor parametrlari](#konstruktor-parametrlari)
- [API](#api)
  - [connect()](#connect)
  - [verifyCode()](#verifycode)
- [Xatolar](#xatolar)
- [Xavfsizlik](#xavfsizlik)
- [Talablar](#talablar)
- [Litsenziya](#litsenziya)

---

## O'rnatish

```bash
npm install @mrsadriddin/authenticator
```

---

## Tezkor boshlash

```javascript
import { Authenticator } from '@mrsadriddin/authenticator'

const auth = new Authenticator({
	internalSecret: 'your-internal-secret', //kiritilishi shart bo'lgan maydon
	projectName: 'my-project', //kiritilishi shart bo'lgan maydon
	baseURL: 'https://your-sso-server.com', // Ihtiyoriy maydon
	debug: true, // Ihtiyoriy maydon
	timeout: 10_000, // Ihtiyoriy maydon
})

// 1. Serverga ulanish
const isConnected = await auth.connect()
if (!isConnected) process.exit(1)

// 2. Kodni tasdiqlash
const result = await auth.verifyCode({ code: '123456' })
console.log(result.user.telegramId)
```

---

## Konstruktor parametrlari

```javascript
new Authenticator({ internalSecret, projectName, baseURL, debug, timeout })
```

| Parametr         | Turi      | Majburiy | Standart | Tavsif                                        |
| ---------------- | --------- | -------- | -------- | --------------------------------------------- |
| `internalSecret` | `string`  | ✅       | —        | SSO server bilan autentifikatsiya uchun kalit |
| `projectName`    | `string`  | ✅       | —        | Loyiha nomi (server loglarida ko'rinadi)      |
| `baseURL`        | `string`  | ✅       | —        | SSO server manzili (masalan: `https://...`)   |
| `debug`          | `boolean` | ❌       | `false`  | Konsolga log chiqarish                        |
| `timeout`        | `number`  | ❌       | `10000`  | So'rov vaqt chegarasi (millisekund)           |

**Misol:**

```javascript
const auth = new Authenticator({
	internalSecret: process.env.SSO_SECRET,
	projectName: process.env.PROJECT_NAME,
	baseURL: process.env.SSO_BASE_URL,
	debug: process.env.NODE_ENV !== 'production',
	timeout: 5_000,
})
```

> ⚠️ `internalSecret` va `baseURL` ni hech qachon kodga to'g'ridan-to'g'ri yozmang. Har doim `.env` faylidan o'qing.

---

## API

### `connect()`

SSO serverga ulanishni tekshiradi (health check).

```javascript
const isConnected = await auth.connect()
// → true | false
```

| Qaytaradi | Tavsif                         |
| --------- | ------------------------------ |
| `true`    | Server ishlayapti, ulandi      |
| `false`   | Server javob bermadi yoki xato |

**Misol:**

```javascript
const ok = await auth.connect()
if (!ok) {
  console.error('SSO serverga ulanib bo'lmadi')
  process.exit(1)
}
```

---

### `verifyCode({ code })`

Foydalanuvchi kiritgan 6 xonali kodni serverda tasdiqlaydi.

```javascript
const result = await auth.verifyCode({ code: '123456' })
```

**Parametr:**

| Parametr | Turi             | Tavsif                   |
| -------- | ---------------- | ------------------------ |
| `code`   | `string\|number` | 6 xonali tasdiqlash kodi |

**Muvaffaqiyatli javob:**

```javascript
{
  success: true,
  user: {
    telegramId: 123456789,
    // ... server tomonidan qaytariladigan boshqa maydonlar
  }
}
```

**Xato holatlari:**

| Holat                      | Xato                                              |
| -------------------------- | ------------------------------------------------- |
| Kod 6 raqamdan iborat emas | `AuthenticatorError: Tasdiqlash kodi 6 ta raqam`  |
| Noto'g'ri kod              | `AuthenticatorError: Kod noto'g'ri yoki yaroqsiz` |
| Server javob bermadi       | `AuthenticatorError: Server javob bermayapti`     |
| HTTP xatosi                | `AuthenticatorError: API Xatosi (HTTP 4xx/5xx)`   |

**Misol:**

```javascript
import { AuthenticatorError } from '@mrsadriddin/authenticator'

try {
	const result = await auth.verifyCode({ code: userInput })
	console.log('Foydalanuvchi:', result.user.telegramId)
} catch (error) {
	if (error instanceof AuthenticatorError) {
		console.error(error.message) // xato matni
		console.error(error.status) // HTTP status (agar mavjud bo'lsa)
	} else {
		throw error
	}
}
```

---

## Xatolar

Barcha kutilgan xatolar `AuthenticatorError` sifatida throw qilinadi.

```javascript
import { AuthenticatorError } from '@mrsadriddin/authenticator'
```

### Xususiyatlar

| Xususiyat | Turi           | Tavsif                                |
| --------- | -------------- | ------------------------------------- |
| `message` | `string`       | Xato matni                            |
| `status`  | `number\|null` | HTTP status kodi (agar mavjud bo'lsa) |
| `name`    | `string`       | Har doim `'AuthenticatorError'`       |

### Tekshirish

```javascript
try {
	await auth.verifyCode({ code: '000000' })
} catch (error) {
	if (error instanceof AuthenticatorError) {
		// kutilgan xato — foydalanuvchiga ko'rsatish mumkin
		console.error(`[${error.status ?? 'CLIENT'}] ${error.message}`)
	} else {
		// kutilmagan xato — yuqoriga uzatish kerak
		throw error
	}
}
```

---

## Xavfsizlik

- `internalSecret` ni `.env` faylida saqlang, hech qachon kodga yozmang
- `baseURL` HTTPS bo'lishi shart (production muhitida)
- `debug: true` ni production da o'chiring — loglar `internalSecret` ni oshkor qilishi mumkin
- `.env` faylini `.gitignore` ga qo'shishni unutmang

**.env misol:**

```env
SSO_SECRET=your-secret-here
SSO_BASE_URL=https://your-sso-server.com
PROJECT_NAME=my-project
```

---

## Talablar

| Muhit   | Versiya   |
| ------- | --------- |
| Node.js | `>= 18.0` |

Node.js 18 dan boshlab quyidagilar built-in mavjud va tashqi kutubxona kerak emas:

- `fetch` — HTTP so'rovlar
- `AbortSignal.timeout` — timeout boshqaruvi
- `Buffer` — encoding

---

## Litsenziya

[MIT](./LICENSE) © [MrSadriddin](https://github.com/mrsadriddin)