mirror of
https://github.com/FromGram/server.git
synced 2026-11-21 02:41:21 +03:00
feat add grammY authentication and store bot
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
BOT_TOKEN=
|
||||
OWNER_IDS=123456789
|
||||
BOT_PUBLIC_USERNAME=
|
||||
PRODUCT_NAME=Telesrv
|
||||
|
||||
GRAMSRV_API=http://127.0.0.1:2399
|
||||
GRAMSRV_TOKEN=
|
||||
GRAMSRV_ACTOR=telesrv-grammy-bot
|
||||
PUBLIC_BASE_URL=https://example.com
|
||||
|
||||
BOT_DB_PATH=./data/bot.sqlite3
|
||||
CODE_HTTP_HOST=127.0.0.1
|
||||
CODE_HTTP_PORT=2800
|
||||
CODE_WEBHOOK_SECRET=replace-with-a-long-random-secret
|
||||
|
||||
REQUIRED_CHANNEL=
|
||||
REQUIRED_CHANNEL_URL=
|
||||
SUPPORT_USERNAME=
|
||||
DEFAULT_LANGUAGE=ru
|
||||
DEFAULT_NUMBER_COUNTRY=RU
|
||||
REFERRAL_BONUS=100
|
||||
DAILY_BONUS=15
|
||||
NOTIFICATION_TTL_DAYS=30
|
||||
@@ -0,0 +1,4 @@
|
||||
node_modules/
|
||||
data/
|
||||
.env
|
||||
npm-debug.log*
|
||||
@@ -0,0 +1,109 @@
|
||||
# grammY authentication and store bot
|
||||
|
||||
This service replaces the former JSON/Python bot with one grammY process and a
|
||||
transactional SQLite database. It deliberately runs independently from
|
||||
`cmd/telesrv`; a bot outage cannot stop MTProto.
|
||||
|
||||
## Included functionality
|
||||
|
||||
- automatic persistent number and initial code on `/start`;
|
||||
- delivery and storage of real login codes through authenticated `POST /code`;
|
||||
- free replacement numbers and paid anonymous `+888` numbers;
|
||||
- Premium, server Stars and collectible username purchases through Telegram Stars;
|
||||
- arbitrary Stars invoices, payment deduplication and a durable sales journal;
|
||||
- account target IDs and three recent recipients;
|
||||
- daily bonuses, referrals and a weighted wheel;
|
||||
- promo codes and button-based giveaways;
|
||||
- support tickets;
|
||||
- language and notification settings;
|
||||
- owner-only statistics, broadcasts, Stars/Premium/bonus grants, invoices,
|
||||
payment refunds, login-code access, support replies, sales and Stars-rate controls;
|
||||
- optional required-channel membership gate.
|
||||
|
||||
The bot token and Admin API token must never be committed. `.env.example`
|
||||
contains names and safe local defaults only.
|
||||
|
||||
## Local run
|
||||
|
||||
Requirements: Node.js 22.13 or newer and a running gramsrv Admin API.
|
||||
|
||||
```bash
|
||||
cd cmd/bots/grammystore
|
||||
cp .env.example .env
|
||||
nano .env
|
||||
npm ci
|
||||
npm test
|
||||
npm start
|
||||
```
|
||||
|
||||
Set `BOT_PUBLIC_USERNAME` so referral links are available before the first
|
||||
`getMe`. `OWNER_IDS` accepts comma-separated Telegram IDs. Users set their
|
||||
gramsrv account ID under Settings; Telegram IDs are not assumed to equal server
|
||||
account IDs.
|
||||
|
||||
`PRODUCT_NAME` controls user-facing product text and defaults to `Telesrv`.
|
||||
Deployment-specific branding belongs in the service environment, not in source.
|
||||
|
||||
## Migrating the former Python bot
|
||||
|
||||
Never open the legacy database directly with the new service because its table
|
||||
names overlap but its columns are incompatible. Keep the old service stopped,
|
||||
copy its database, and create a separate destination:
|
||||
|
||||
```bash
|
||||
npm run migrate:legacy -- /path/to/legacy.sqlite3 /path/to/new.sqlite3
|
||||
```
|
||||
|
||||
The command refuses to overwrite its source or an existing destination. It
|
||||
preserves users, bonus balances, referrals, numbers, current login codes and
|
||||
support messages. Keep the legacy database backup for historical orders and
|
||||
broadcast drafts, which have no equivalent in the new Telegram Stars journal.
|
||||
|
||||
## Login-code webhook
|
||||
|
||||
Configure gramsrv's code-delivery webhook for:
|
||||
|
||||
```text
|
||||
TELESRV_PHONE_CODE_DELIVERY_PROVIDER=webhook
|
||||
TELESRV_OTP_WEBHOOK_URL=http://127.0.0.1:2800/v1/otp/deliveries
|
||||
TELESRV_OTP_WEBHOOK_SECRET=<same value as CODE_WEBHOOK_SECRET>
|
||||
```
|
||||
|
||||
gramsrv sends its version-1 JSON envelope and signs the exact request body as
|
||||
`X-Telesrv-Signature: sha256=<HMAC-SHA256(timestamp + "." + body)>`. The bot
|
||||
checks that signature, a five-minute timestamp window and `Idempotency-Key`.
|
||||
For example, the body contains:
|
||||
|
||||
```json
|
||||
{"version":"1","delivery_id":"...","purpose":"login_sms","channel":"sms","recipient":"+79991234567","code":"12345","expires_at":"2026-08-09T12:00:00Z","expires_in":300}
|
||||
```
|
||||
|
||||
The endpoint is loopback-only by default. It rejects requests without the
|
||||
HMAC secret, stores each delivery idempotently and returns HTTP 202 immediately;
|
||||
Telegram delivery then runs asynchronously for the number owner and explicitly
|
||||
granted support viewers. A slow Bot API therefore cannot turn `auth.sendCode`
|
||||
into a server-side timeout. `/healthz` is read-only.
|
||||
|
||||
## Linux install
|
||||
|
||||
```bash
|
||||
sudo useradd --system --home /var/lib/telesrv-grammy-bot --shell /usr/sbin/nologin telesrv-bot || true
|
||||
sudo install -d -o telesrv-bot -g telesrv-bot -m 0750 /opt/telesrv-grammy-bot /var/lib/telesrv-grammy-bot
|
||||
sudo cp -a package.json package-lock.json src /opt/telesrv-grammy-bot/
|
||||
cd /opt/telesrv-grammy-bot
|
||||
sudo npm ci --omit=dev
|
||||
sudo cp .env.example /etc/telesrv-grammy-bot.env
|
||||
sudo chmod 0600 /etc/telesrv-grammy-bot.env
|
||||
sudo cp deploy/telesrv-grammy-bot.service /etc/systemd/system/
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now telesrv-grammy-bot
|
||||
sudo journalctl -u telesrv-grammy-bot -f
|
||||
```
|
||||
|
||||
Use `BOT_DB_PATH=/var/lib/telesrv-grammy-bot/bot.sqlite3` in the production env.
|
||||
Back up the database with SQLite's online backup command or while the service is
|
||||
stopped; include `/etc/telesrv-grammy-bot.env` in a separate encrypted secret
|
||||
backup.
|
||||
|
||||
The systemd unit intentionally has no hosting-specific values. Do not deploy it
|
||||
until the local branch has been reviewed and merged.
|
||||
@@ -0,0 +1,23 @@
|
||||
[Unit]
|
||||
Description=Telesrv grammY store and authentication bot
|
||||
After=network-online.target gramsrv.service
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=telesrv-bot
|
||||
Group=telesrv-bot
|
||||
WorkingDirectory=/opt/telesrv-grammy-bot
|
||||
EnvironmentFile=/etc/telesrv-grammy-bot.env
|
||||
ExecStart=/usr/bin/node /opt/telesrv-grammy-bot/src/index.js
|
||||
Restart=on-failure
|
||||
RestartSec=3
|
||||
TimeoutStopSec=20
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
ReadWritePaths=/var/lib/telesrv-grammy-bot
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
Generated
+138
@@ -0,0 +1,138 @@
|
||||
{
|
||||
"name": "telesrv-grammy-store-bot",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "telesrv-grammy-store-bot",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"dotenv": "17.4.2",
|
||||
"grammy": "1.45.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.13"
|
||||
}
|
||||
},
|
||||
"node_modules/@grammyjs/types": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@grammyjs/types/-/types-4.0.0.tgz",
|
||||
"integrity": "sha512-Z8lDLTvOlo12e5Vnly/vQh3JC9ppaitS1dGZ3w068gNitOd/y8tTSiib+Xm38aBGbtYGmUZwOc6afYrLs2CSTg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/abort-controller": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",
|
||||
"integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"event-target-shim": "^5.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.5"
|
||||
}
|
||||
},
|
||||
"node_modules/debug": {
|
||||
"version": "4.4.3",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
|
||||
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ms": "^2.1.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"supports-color": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/dotenv": {
|
||||
"version": "17.4.2",
|
||||
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz",
|
||||
"integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==",
|
||||
"license": "BSD-2-Clause",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://dotenvx.com"
|
||||
}
|
||||
},
|
||||
"node_modules/event-target-shim": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
|
||||
"integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/grammy": {
|
||||
"version": "1.45.1",
|
||||
"resolved": "https://registry.npmjs.org/grammy/-/grammy-1.45.1.tgz",
|
||||
"integrity": "sha512-Y4VL/hqJMZZxwlUr5ZgM68CFu2iIeEkNLR1cY3+Ww68CIvWARDsoXFix7+31rmyC0+7L85ZI+Pq3E5JSG5+nLQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@grammyjs/types": "4.0.0",
|
||||
"abort-controller": "^3.0.0",
|
||||
"debug": "^4.4.3",
|
||||
"node-fetch": "^2.7.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^12.20.0 || >=14.13.1"
|
||||
}
|
||||
},
|
||||
"node_modules/ms": {
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/node-fetch": {
|
||||
"version": "2.7.0",
|
||||
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
|
||||
"integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"whatwg-url": "^5.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "4.x || >=6.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"encoding": "^0.1.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"encoding": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/tr46": {
|
||||
"version": "0.0.3",
|
||||
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
|
||||
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/webidl-conversions": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
|
||||
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
|
||||
"license": "BSD-2-Clause"
|
||||
},
|
||||
"node_modules/whatwg-url": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
|
||||
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tr46": "~0.0.3",
|
||||
"webidl-conversions": "^3.0.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"name": "telesrv-grammy-store-bot",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"engines": { "node": ">=22.13" },
|
||||
"scripts": {
|
||||
"start": "node src/index.js",
|
||||
"check": "node --check src/index.js && node --check src/bot.js",
|
||||
"migrate:legacy": "node scripts/migrate-legacy-db.js",
|
||||
"test": "node --test"
|
||||
},
|
||||
"dependencies": {
|
||||
"dotenv": "17.4.2",
|
||||
"grammy": "1.45.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import { BotDatabase } from "../src/db.js";
|
||||
|
||||
function dayFromUnix(value) {
|
||||
const seconds = Number(value);
|
||||
return Number.isSafeInteger(seconds) && seconds > 0 ? new Date(seconds * 1000).toISOString().slice(0, 10) : "";
|
||||
}
|
||||
|
||||
function countryFor(phone) {
|
||||
if (phone.startsWith("+888")) return "ANON";
|
||||
if (phone.startsWith("+1")) return "US";
|
||||
return "RU";
|
||||
}
|
||||
|
||||
function requireLegacySchema(db) {
|
||||
const columns = db.prepare("PRAGMA table_info(users)").all().map((row) => row.name);
|
||||
if (!columns.includes("tg_id") || columns.includes("telegram_id")) {
|
||||
throw new Error("source database is not the supported legacy bot schema");
|
||||
}
|
||||
}
|
||||
|
||||
export function migrateLegacy(sourcePath, destinationPath) {
|
||||
sourcePath = path.resolve(sourcePath);
|
||||
destinationPath = path.resolve(destinationPath);
|
||||
if (sourcePath === destinationPath) throw new Error("source and destination must be different files");
|
||||
if (!existsSync(sourcePath)) throw new Error(`source database does not exist: ${sourcePath}`);
|
||||
if (existsSync(destinationPath)) throw new Error(`destination already exists: ${destinationPath}`);
|
||||
|
||||
const legacy = new DatabaseSync(sourcePath, { readOnly: true });
|
||||
let target;
|
||||
try {
|
||||
requireLegacySchema(legacy);
|
||||
target = new BotDatabase(destinationPath);
|
||||
const users = legacy.prepare("SELECT * FROM users ORDER BY created_at,tg_id").all();
|
||||
const userIDs = new Set(users.map((row) => Number(row.tg_id)));
|
||||
|
||||
target.tx(() => {
|
||||
const insertUser = target.db.prepare(`INSERT INTO users(
|
||||
telegram_id,chat_id,username,first_name,server_user_id,language,notifications,bonus,
|
||||
referred_by,referral_count,daily_day,created_at,updated_at
|
||||
) VALUES(?,?,?,?,0,?,?,?,?,?,?,?,?)`);
|
||||
for (const row of users) {
|
||||
insertUser.run(
|
||||
Number(row.tg_id), Number(row.tg_id), row.username ?? "", row.first_name ?? "",
|
||||
row.language === "en" ? "en" : "ru", Number(row.notifications) ? 1 : 0,
|
||||
Math.max(0, Number(row.bonuses) || 0), null, Math.max(0, Number(row.referrals_count) || 0),
|
||||
dayFromUnix(row.last_daily_at), Number(row.created_at) || 0, Number(row.updated_at) || Number(row.created_at) || 0,
|
||||
);
|
||||
}
|
||||
const setReferrer = target.db.prepare("UPDATE users SET referred_by=? WHERE telegram_id=?");
|
||||
for (const row of users) {
|
||||
const referrer = Number(row.referrer_id);
|
||||
if (referrer > 0 && referrer !== Number(row.tg_id) && userIDs.has(referrer)) setReferrer.run(referrer, Number(row.tg_id));
|
||||
}
|
||||
|
||||
const activeOwners = new Set();
|
||||
const insertNumber = target.db.prepare(`INSERT INTO numbers(
|
||||
phone,display,format,country,owner_id,chat_id,is_current,login_code,code_expires_at,created_at
|
||||
) VALUES(?,?,?,?,?,?,?,?,?,?)`);
|
||||
const oldNumbers = legacy.prepare("SELECT * FROM numbers ORDER BY active DESC,created_at DESC,phone").all();
|
||||
const oldUsers = new Map(users.map((row) => [Number(row.tg_id), row]));
|
||||
for (const row of oldNumbers) {
|
||||
const ownerID = Number(row.tg_id);
|
||||
if (!userIDs.has(ownerID)) continue;
|
||||
const current = Number(row.active) !== 0 && !activeOwners.has(ownerID);
|
||||
if (current) activeOwners.add(ownerID);
|
||||
const oldUser = oldUsers.get(ownerID);
|
||||
const code = current ? String(oldUser?.latest_code ?? "") : "";
|
||||
const expires = current ? Math.max(0, Number(oldUser?.code_expires_at) || 0) : 0;
|
||||
const phone = String(row.phone);
|
||||
insertNumber.run(phone, phone, "legacy", countryFor(phone), ownerID, ownerID, current ? 1 : 0, code, expires, Number(row.created_at) || 0);
|
||||
}
|
||||
|
||||
const insertSupport = target.db.prepare(`INSERT INTO support_messages(
|
||||
id,telegram_id,chat_id,text,status,created_at,answered_at
|
||||
) VALUES(?,?,?,?,?,?,0)`);
|
||||
for (const row of legacy.prepare("SELECT * FROM support_messages ORDER BY id").all()) {
|
||||
const telegramID = Number(row.tg_id);
|
||||
if (userIDs.has(telegramID)) insertSupport.run(Number(row.id), telegramID, telegramID, row.text ?? "", row.status ?? "open", Number(row.created_at) || 0);
|
||||
}
|
||||
});
|
||||
|
||||
// Leave a self-contained database file for the handoff. BotDatabase will
|
||||
// switch it back to WAL mode when the service first opens it.
|
||||
target.db.exec("PRAGMA wal_checkpoint(TRUNCATE); PRAGMA journal_mode=DELETE");
|
||||
return {
|
||||
users: target.db.prepare("SELECT count(*) count FROM users").get().count,
|
||||
numbers: target.db.prepare("SELECT count(*) count FROM numbers").get().count,
|
||||
supportMessages: target.db.prepare("SELECT count(*) count FROM support_messages").get().count,
|
||||
};
|
||||
} finally {
|
||||
target?.close();
|
||||
legacy.close();
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url) {
|
||||
const [, , source, destination] = process.argv;
|
||||
if (!source || !destination) {
|
||||
console.error("usage: node scripts/migrate-legacy-db.js LEGACY_DB NEW_DB");
|
||||
process.exitCode = 2;
|
||||
} else {
|
||||
console.log(JSON.stringify(migrateLegacy(source, destination)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
import { Bot, GrammyError, HttpError, InlineKeyboard } from "grammy";
|
||||
import { randomInt } from "node:crypto";
|
||||
import { buildPayload, findProduct, KINDS, normalizeUsername, parsePayload, productsOfKind } from "./catalog.js";
|
||||
|
||||
const spinPrizes = [{ amount: 50, weight: 250 }, { amount: 100, weight: 130 }, { amount: 500, weight: 50 }, { amount: 1000, weight: 30 }, { amount: 10000, weight: 10 }, { amount: 15, weight: 530 }];
|
||||
const text = {
|
||||
ru: {
|
||||
hello: "👋 <b>Добро пожаловать!</b>\n\nЗдесь можно получать номера и коды, покупать Stars, Premium и коллекционные активы.",
|
||||
menu: "🏠 <b>Главное меню</b>", numbers: "📱 <b>Ваши номера</b>", noCode: "Код ещё не поступал.",
|
||||
shop: "🛒 <b>Магазин</b>\nВыберите раздел:", bonuses: "🎁 <b>Бонусы</b>", settings: "⚙️ <b>Настройки</b>",
|
||||
support: "💬 Отправьте одним сообщением вопрос для поддержки.", target: "Введите числовой ID пользователя в {product}.",
|
||||
account: "Введите ваш числовой ID аккаунта {product}. Он будет использоваться для бонусов и покупок себе.",
|
||||
},
|
||||
en: {
|
||||
hello: "👋 <b>Welcome!</b>\n\nGet numbers and login codes, or buy Stars, Premium and collectibles.",
|
||||
menu: "🏠 <b>Main menu</b>", numbers: "📱 <b>Your numbers</b>", noCode: "No login code has arrived yet.",
|
||||
shop: "🛒 <b>Store</b>\nChoose a section:", bonuses: "🎁 <b>Bonuses</b>", settings: "⚙️ <b>Settings</b>",
|
||||
support: "💬 Send your support question in one message.", target: "Enter the numeric {product} user ID.",
|
||||
account: "Enter your numeric {product} account ID. It is used for bonuses and purchases for yourself.",
|
||||
},
|
||||
};
|
||||
|
||||
function escapeHTML(value) { return String(value ?? "").replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """); }
|
||||
function language(db, id, fallback) { return db.user(id)?.language ?? fallback; }
|
||||
function t(db, id, fallback, key, productName = "Telesrv") { return text[language(db, id, fallback)][key].replaceAll("{product}", productName); }
|
||||
function isOwner(config, id) { return config.ownerIDs.has(id); }
|
||||
function userName(from) { return from.username ? `@${from.username}` : [from.first_name, from.last_name].filter(Boolean).join(" "); }
|
||||
function initialLanguage(from, fallback) { const code = String(from?.language_code ?? "").toLowerCase(); return code.startsWith("ru") ? "ru" : code ? "en" : fallback; }
|
||||
|
||||
function mainKeyboard(admin = false) {
|
||||
const kb = new InlineKeyboard().text("📱 Номера", "menu:numbers").text("🛒 Магазин", "menu:shop").row()
|
||||
.text("🎁 Бонусы", "menu:bonuses").text("👥 Рефералы", "menu:referrals").row()
|
||||
.text("💬 Поддержка", "menu:support").text("⚙️ Настройки", "menu:settings");
|
||||
if (admin) kb.row().text("🛡 Админ-панель", "admin:menu");
|
||||
return kb;
|
||||
}
|
||||
function backKeyboard(target = "menu:home") { return new InlineKeyboard().text("‹ Назад", target); }
|
||||
function shopKeyboard() { return new InlineKeyboard().text("👑 Premium", "shop:premium").text("⭐ Stars", "shop:stars").row().text("📱 +888", "shop:number").text("💎 NFT username", "shop:username").row().text("‹ Назад", "menu:home"); }
|
||||
function settingsKeyboard(user) { return new InlineKeyboard().text("🆔 ID аккаунта", "settings:account").row().text("🌐 Русский", "settings:lang:ru").text("🌐 English", "settings:lang:en").row().text(user.notifications ? "🔔 Уведомления: да" : "🔕 Уведомления: нет", "settings:notifications").row().text("‹ Назад", "menu:home"); }
|
||||
function adminKeyboard() { return new InlineKeyboard().text("📊 Статистика", "admin:stats").text("📣 Рассылка", "admin:broadcast").row().text("⭐ Выдать Stars", "admin:stars").text("💎 Выдать Premium", "admin:premium").row().text("🎟 Промокод", "admin:promo").text("🎁 Розыгрыш", "admin:giveaway").row().text("🎁 Выдать бонус", "admin:bonus").text("🧾 Счёт", "admin:invoice").row().text("📨 Доступ к кодам", "admin:access").text("↩️ Возврат", "admin:refund").row().text("💬 Ответить", "admin:reply").text("📈 Продажи", "admin:sales").row().text("⚙️ Курс Stars", "admin:rate").row().text("‹ Назад", "menu:home"); }
|
||||
|
||||
async function editOrReply(ctx, message, keyboard = undefined) {
|
||||
const options = { parse_mode: "HTML", link_preview_options: { is_disabled: true }, reply_markup: keyboard };
|
||||
if (ctx.callbackQuery?.message) {
|
||||
try { return await ctx.editMessageText(message, options); } catch (error) { if (!String(error.description ?? error).includes("message is not modified")) throw error; }
|
||||
}
|
||||
return ctx.reply(message, options);
|
||||
}
|
||||
|
||||
async function subscribed(ctx, config) {
|
||||
if (!config.requiredChannel || isOwner(config, ctx.from.id)) return true;
|
||||
try { const member = await ctx.api.getChatMember(config.requiredChannel, ctx.from.id); return ["creator", "administrator", "member", "restricted"].includes(member.status); }
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
async function subscriptionGate(ctx, config) {
|
||||
const kb = new InlineKeyboard();
|
||||
if (config.requiredChannelURL) kb.url("📣 Открыть канал", config.requiredChannelURL).row();
|
||||
kb.text("✅ Я подписался", "subscription:check");
|
||||
await editOrReply(ctx, "🔒 Для использования бота подпишитесь на обязательный канал, затем нажмите кнопку проверки.", kb);
|
||||
}
|
||||
|
||||
function parseStartRef(ctx) {
|
||||
const match = String(ctx.match ?? "").match(/^ref_(\d+)$/); return match ? Number(match[1]) : 0;
|
||||
}
|
||||
|
||||
function productText(product) {
|
||||
const extra = product.kind === KINDS.username ? `\nСтавка: <b>${product.bid} TON</b>` : product.kind === KINDS.stars ? `\nБудет начислено: <b>${product.starsAmount}</b>` : "";
|
||||
return `<b>${escapeHTML(product.title)}</b>\n\n${escapeHTML(product.description)}\n\nЦена: <b>${product.starsPrice} ⭐</b>${extra}`;
|
||||
}
|
||||
|
||||
function productKeyboard(product, db, buyerID) {
|
||||
const kb = new InlineKeyboard();
|
||||
if (product.kind === KINDS.number) return kb.text(`Купить за ${product.starsPrice} ⭐`, `buy:${product.code}:0`).row().text("‹ Назад", `shop:${product.kind}`);
|
||||
const selfID = db.user(buyerID)?.server_user_id ?? 0;
|
||||
if (selfID > 0) kb.text("Купить себе", `buy:${product.code}:${selfID}`).row();
|
||||
kb.text("Подарить / другой ID", `target:${product.code}`).row();
|
||||
for (const id of db.recentRecipients(buyerID)) kb.text(`ID ${id}`, `buy:${product.code}:${id}`);
|
||||
return kb.row().text("‹ Назад", `shop:${product.kind}`);
|
||||
}
|
||||
|
||||
async function sendInvoice(ctx, product, targetUserID, extra = "") {
|
||||
await ctx.api.sendInvoice(ctx.chat.id, product.title, product.description, buildPayload(product.code, targetUserID, extra), "XTR", [{ label: product.title, amount: product.starsPrice }]);
|
||||
}
|
||||
|
||||
function rollPrize() {
|
||||
const total = spinPrizes.reduce((sum, value) => sum + value.weight, 0); let value = randomInt(total);
|
||||
for (const prize of spinPrizes) { value -= prize.weight; if (value < 0) return prize.amount; }
|
||||
return 15;
|
||||
}
|
||||
|
||||
export function createBot({ config, db, gramsrv }) {
|
||||
const bot = new Bot(config.botToken);
|
||||
|
||||
bot.use(async (ctx, next) => {
|
||||
if (ctx.from && ctx.chat) db.upsertUser(ctx.from, ctx.chat.id, initialLanguage(ctx.from, config.defaultLanguage));
|
||||
await next();
|
||||
});
|
||||
|
||||
bot.command("start", async (ctx) => {
|
||||
const referrer = parseStartRef(ctx);
|
||||
const existed = db.user(ctx.from.id);
|
||||
db.upsertUser(ctx.from, ctx.chat.id, initialLanguage(ctx.from, config.defaultLanguage), referrer, config.referralBonus);
|
||||
if (!(await subscribed(ctx, config))) return subscriptionGate(ctx, config);
|
||||
const number = db.createNumber(ctx.from.id, ctx.chat.id, "free", config.defaultNumberCountry, false);
|
||||
const referralNotice = !existed && referrer > 0 ? "\n\n✅ Реферальное приглашение учтено." : "";
|
||||
await ctx.reply(`${t(db, ctx.from.id, config.defaultLanguage, "hello")}\n\n📞 Ваш номер: <code>${escapeHTML(number.display)}</code>\n🔑 Начальный код: <code>${number.login_code}</code>${referralNotice}`, { parse_mode: "HTML", reply_markup: mainKeyboard(isOwner(config, ctx.from.id)) });
|
||||
});
|
||||
|
||||
bot.command("menu", async (ctx) => editOrReply(ctx, t(db, ctx.from.id, config.defaultLanguage, "menu"), mainKeyboard(isOwner(config, ctx.from.id))));
|
||||
bot.command("admin", async (ctx) => { if (isOwner(config, ctx.from.id)) await editOrReply(ctx, "🛡 <b>Админ-панель</b>", adminKeyboard()); });
|
||||
bot.command("promo_code", async (ctx) => {
|
||||
const [code, rawID] = String(ctx.match ?? "").trim().split(/\s+/); const serverID = Number(rawID || db.user(ctx.from.id)?.server_user_id);
|
||||
if (!code || !Number.isSafeInteger(serverID) || serverID <= 0) return ctx.reply(`Формат: /promo_code CODE ${config.productName.toUpperCase()}_ID`);
|
||||
try {
|
||||
const promo = db.claimPromo(code, ctx.from.id);
|
||||
try { await gramsrv.grantStars(serverID, promo.stars_amount, `Promo ${code}`, `promo:${code.toLowerCase()}:${ctx.from.id}`); }
|
||||
catch (error) { db.releaseCampaignClaim("promo", code.toLowerCase(), ctx.from.id); throw error; }
|
||||
await ctx.reply(`✅ Начислено ${promo.stars_amount} Stars.`);
|
||||
} catch (error) { await ctx.reply(`⚠️ ${escapeHTML(error.message)}`, { parse_mode: "HTML" }); }
|
||||
});
|
||||
|
||||
bot.on("pre_checkout_query", async (ctx) => {
|
||||
try {
|
||||
if (ctx.preCheckoutQuery.currency !== "XTR") throw new Error("unsupported currency");
|
||||
if (!ctx.preCheckoutQuery.invoice_payload.startsWith("custom|")) {
|
||||
const parsed = parsePayload(ctx.preCheckoutQuery.invoice_payload); const product = findProduct(parsed.code, db.starsRate());
|
||||
if (!product || product.starsPrice !== ctx.preCheckoutQuery.total_amount) throw new Error("product price changed");
|
||||
}
|
||||
await ctx.answerPreCheckoutQuery(true);
|
||||
}
|
||||
catch { await ctx.answerPreCheckoutQuery(false, { error_message: "Некорректный или устаревший заказ." }); }
|
||||
});
|
||||
|
||||
async function fulfill(product, recipientID, buyer, chatID, chargeID, extra = "") {
|
||||
if (product.kind !== KINDS.number && (!Number.isSafeInteger(recipientID) || recipientID <= 0)) throw new Error(`recipient ${config.productName} ID is invalid`);
|
||||
if (db.saleByCharge(chargeID)) return;
|
||||
const key = `payment:${chargeID}:${product.code}`;
|
||||
let number = null;
|
||||
if (product.kind === KINDS.premium) await gramsrv.grantPremium(recipientID, product.months, "Telegram bot purchase", key);
|
||||
else if (product.kind === KINDS.stars) await gramsrv.grantStars(recipientID, product.starsAmount, "Telegram bot purchase", key);
|
||||
else if (product.kind === KINDS.username) {
|
||||
const username = normalizeUsername(extra); if (!username) throw new Error("collectible username is invalid");
|
||||
await gramsrv.mintUsername(recipientID, username, product.bid, key);
|
||||
} else if (product.kind === KINDS.number) {
|
||||
number = db.createNumber(buyer.id, chatID, product.numberFormat, "ANON", true);
|
||||
}
|
||||
db.addSale({ product: product.code, title: product.title, starsPrice: product.starsPrice, recipientID, buyerID: buyer.id, buyerName: userName(buyer), chargeID });
|
||||
if (number) await bot.api.sendMessage(chatID, `✅ Номер зарезервирован: <code>${escapeHTML(number.display)}</code>`, { parse_mode: "HTML" }).catch(() => {});
|
||||
else await bot.api.sendMessage(chatID, `✅ <b>${escapeHTML(product.title)}</b> выдано пользователю <code>${recipientID}</code>.`, { parse_mode: "HTML" }).catch(() => {});
|
||||
}
|
||||
|
||||
bot.on("message:successful_payment", async (ctx) => {
|
||||
const payment = ctx.message.successful_payment;
|
||||
if (!db.beginPayment(payment.telegram_payment_charge_id, ctx.from.id, payment.invoice_payload, payment.total_amount)) return;
|
||||
try {
|
||||
if (payment.invoice_payload.startsWith("custom|")) {
|
||||
const title = Buffer.from(payment.invoice_payload.slice(7), "base64url").toString("utf8");
|
||||
db.addSale({ product: "custom", title, starsPrice: payment.total_amount, recipientID: ctx.from.id, buyerID: ctx.from.id, buyerName: userName(ctx.from), chargeID: payment.telegram_payment_charge_id });
|
||||
await ctx.reply(`✅ Оплата «${escapeHTML(title)}» получена.`, { parse_mode: "HTML" });
|
||||
} else {
|
||||
const parsed = parsePayload(payment.invoice_payload);
|
||||
const product = findProduct(parsed.code, db.starsRate()); if (!product) throw new Error("product no longer exists");
|
||||
if (payment.currency !== "XTR" || payment.total_amount !== product.starsPrice) throw new Error("paid amount does not match the product");
|
||||
const recipient = parsed.targetUserID || db.user(ctx.from.id)?.server_user_id || 0;
|
||||
await fulfill(product, recipient, ctx.from, ctx.chat.id, payment.telegram_payment_charge_id, parsed.extra);
|
||||
}
|
||||
db.finishPayment(payment.telegram_payment_charge_id);
|
||||
} catch (error) {
|
||||
db.failPayment(payment.telegram_payment_charge_id, error);
|
||||
await ctx.reply(`⚠️ Оплата получена, но автоматическая выдача не завершена. Передайте поддержке чек <code>${escapeHTML(payment.telegram_payment_charge_id)}</code>.`, { parse_mode: "HTML" });
|
||||
for (const owner of config.ownerIDs) await bot.api.sendMessage(owner, `⚠️ Ошибка выдачи ${escapeHTML(payment.telegram_payment_charge_id)}: ${escapeHTML(error.message)}`, { parse_mode: "HTML" }).catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
bot.callbackQuery(/^subscription:check$/, async (ctx) => { await ctx.answerCallbackQuery(); if (await subscribed(ctx, config)) await editOrReply(ctx, t(db, ctx.from.id, config.defaultLanguage, "menu"), mainKeyboard(isOwner(config, ctx.from.id))); else await subscriptionGate(ctx, config); });
|
||||
bot.callbackQuery(/^menu:(.+)$/, async (ctx) => {
|
||||
await ctx.answerCallbackQuery(); const page = ctx.match[1]; const user = db.user(ctx.from.id);
|
||||
if (page === "home") return editOrReply(ctx, t(db, ctx.from.id, config.defaultLanguage, "menu"), mainKeyboard(isOwner(config, ctx.from.id)));
|
||||
if (page === "numbers") {
|
||||
const numbers = db.numbers(ctx.from.id); const current = db.currentNumber(ctx.from.id);
|
||||
const list = numbers.slice(0, 10).map((number) => `${number.is_current ? "▶️" : "▫️"} <code>${escapeHTML(number.display)}</code>`).join("\n");
|
||||
const code = current?.login_code && current.code_expires_at >= Math.floor(Date.now() / 1000) ? `<code>${current.login_code}</code>` : t(db, ctx.from.id, config.defaultLanguage, "noCode");
|
||||
return editOrReply(ctx, `${t(db, ctx.from.id, config.defaultLanguage, "numbers")}\n\n${list || "—"}\n\n🔑 ${code}`, new InlineKeyboard().text("🔄 Новый бесплатный номер", "numbers:new").row().text("‹ Назад", "menu:home"));
|
||||
}
|
||||
if (page === "shop") return editOrReply(ctx, t(db, ctx.from.id, config.defaultLanguage, "shop"), shopKeyboard());
|
||||
if (page === "bonuses") return editOrReply(ctx, `${t(db, ctx.from.id, config.defaultLanguage, "bonuses")}\n\nБаланс: <b>${user.bonus}</b>\nРефералов: <b>${user.referral_count}</b>`, new InlineKeyboard().text("🎁 Ежедневный бонус", "bonus:daily").text("🎡 Рулетка", "bonus:spin").row().text("‹ Назад", "menu:home"));
|
||||
if (page === "referrals") {
|
||||
const username = config.publicUsername || bot.botInfo?.username || "bot"; const link = `https://t.me/${username}?start=ref_${ctx.from.id}`;
|
||||
return editOrReply(ctx, `👥 <b>Реферальная система</b>\n\nПриглашено: <b>${user.referral_count}</b>\nБонус за приглашение: <b>${config.referralBonus}</b>\n\n<code>${link}</code>`, backKeyboard());
|
||||
}
|
||||
if (page === "support") { db.setPending(ctx.from.id, "support"); return editOrReply(ctx, t(db, ctx.from.id, config.defaultLanguage, "support"), backKeyboard()); }
|
||||
if (page === "settings") return editOrReply(ctx, t(db, ctx.from.id, config.defaultLanguage, "settings"), settingsKeyboard(user));
|
||||
});
|
||||
|
||||
bot.callbackQuery(/^numbers:new$/, async (ctx) => { await ctx.answerCallbackQuery(); await editOrReply(ctx, "🌍 Выберите страну нового бесплатного номера:", new InlineKeyboard().text("🇷🇺 Россия", "numbers:new:RU").text("🇺🇸 США", "numbers:new:US").row().text("‹ Назад", "menu:numbers")); });
|
||||
bot.callbackQuery(/^numbers:new:(RU|US)$/, async (ctx) => { await ctx.answerCallbackQuery(); const number = db.createNumber(ctx.from.id, ctx.chat.id, "free", ctx.match[1], true); await editOrReply(ctx, `✅ Новый номер: <code>${escapeHTML(number.display)}</code>\nНачальный код: <code>${number.login_code}</code>`, backKeyboard("menu:numbers")); });
|
||||
bot.callbackQuery(/^shop:(premium|stars|number|username)$/, async (ctx) => { await ctx.answerCallbackQuery(); const kind = ctx.match[1]; const kb = new InlineKeyboard(); for (const product of productsOfKind(kind, db.starsRate())) kb.text(`${product.title} · ${product.starsPrice}⭐`, `product:${product.code}`).row(); if (kind === KINDS.stars) kb.text("✍️ Другая сумма", "stars:custom").row(); kb.text("‹ Назад", "menu:shop"); await editOrReply(ctx, "Выберите товар:", kb); });
|
||||
bot.callbackQuery(/^stars:custom$/, async (ctx) => { await ctx.answerCallbackQuery(); db.setPending(ctx.from.id, "stars_amount"); await editOrReply(ctx, "Сколько Telegram Stars вы хотите потратить? Введите число от 1 до 99999.", backKeyboard("shop:stars")); });
|
||||
bot.callbackQuery(/^product:(.+)$/, async (ctx) => { await ctx.answerCallbackQuery(); const product = findProduct(ctx.match[1], db.starsRate()); if (!product) return; await editOrReply(ctx, productText(product), productKeyboard(product, db, ctx.from.id)); });
|
||||
bot.callbackQuery(/^target:(.+)$/, async (ctx) => { await ctx.answerCallbackQuery(); db.setPending(ctx.from.id, "target", { productCode: ctx.match[1] }); await editOrReply(ctx, t(db, ctx.from.id, config.defaultLanguage, "target", config.productName), backKeyboard(`product:${ctx.match[1]}`)); });
|
||||
bot.callbackQuery(/^buy:([^:]+):(\d+)$/, async (ctx) => {
|
||||
await ctx.answerCallbackQuery(); const product = findProduct(ctx.match[1], db.starsRate()); const targetID = Number(ctx.match[2]); if (!product) return;
|
||||
if (product.kind === KINDS.username) { db.setPending(ctx.from.id, "username", { productCode: product.code, targetID }); return editOrReply(ctx, "Введите желаемый username (без @):", backKeyboard(`product:${product.code}`)); }
|
||||
if (targetID > 0 && targetID !== db.user(ctx.from.id)?.server_user_id) db.rememberRecipient(ctx.from.id, targetID);
|
||||
if (isOwner(config, ctx.from.id)) { await fulfill(product, targetID, ctx.from, ctx.chat.id, `owner-${Date.now()}`); return; }
|
||||
await sendInvoice(ctx, product, targetID);
|
||||
});
|
||||
|
||||
bot.callbackQuery(/^settings:lang:(ru|en)$/, async (ctx) => { db.setLanguage(ctx.from.id, ctx.match[1]); await ctx.answerCallbackQuery({ text: "OK" }); await editOrReply(ctx, t(db, ctx.from.id, config.defaultLanguage, "settings"), settingsKeyboard(db.user(ctx.from.id))); });
|
||||
bot.callbackQuery(/^settings:notifications$/, async (ctx) => { const enabled = db.toggleNotifications(ctx.from.id); await ctx.answerCallbackQuery({ text: enabled ? "Включены" : "Выключены" }); await editOrReply(ctx, t(db, ctx.from.id, config.defaultLanguage, "settings"), settingsKeyboard(db.user(ctx.from.id))); });
|
||||
bot.callbackQuery(/^settings:account$/, async (ctx) => { await ctx.answerCallbackQuery(); db.setPending(ctx.from.id, "account"); await editOrReply(ctx, t(db, ctx.from.id, config.defaultLanguage, "account", config.productName), backKeyboard("menu:settings")); });
|
||||
bot.callbackQuery(/^bonus:daily$/, async (ctx) => { const result = db.claimDaily(ctx.from.id, config.dailyBonus); await ctx.answerCallbackQuery({ text: result.claimed ? `+${config.dailyBonus}` : "Уже получен сегодня" }); await editOrReply(ctx, `${t(db, ctx.from.id, config.defaultLanguage, "bonuses")}\n\nБаланс: <b>${result.balance}</b>`, backKeyboard("menu:bonuses")); });
|
||||
bot.callbackQuery(/^bonus:spin$/, async (ctx) => {
|
||||
await ctx.answerCallbackQuery(); const user = db.user(ctx.from.id); if (!user.server_user_id) { db.setPending(ctx.from.id, "account"); return editOrReply(ctx, t(db, ctx.from.id, config.defaultLanguage, "account", config.productName), backKeyboard("menu:bonuses")); }
|
||||
try { const award = db.reserveSpin(ctx.from.id, user.server_user_id, rollPrize()); await gramsrv.grantStars(user.server_user_id, award.prize, "Daily bot wheel", `spin:${ctx.from.id}:${award.day}`); db.finishSpin(ctx.from.id, award.day); await editOrReply(ctx, `🎉 Вы выиграли <b>${award.prize} Stars</b>!`, backKeyboard("menu:bonuses")); }
|
||||
catch (error) { await editOrReply(ctx, `⚠️ ${escapeHTML(error.message)}`, backKeyboard("menu:bonuses")); }
|
||||
});
|
||||
|
||||
bot.callbackQuery(/^giveaway:([a-f0-9]+)$/, async (ctx) => { await ctx.answerCallbackQuery(); const user = db.user(ctx.from.id); if (!user.server_user_id) return ctx.reply(`Сначала укажите ${config.productName} ID в настройках.`); const id = ctx.match[1]; try { const item = db.claimGiveaway(id, ctx.from.id); try { await gramsrv.grantStars(user.server_user_id, item.stars_amount, `Giveaway ${id}`, `giveaway:${id}:${ctx.from.id}`); } catch (error) { db.releaseCampaignClaim("giveaway", id, ctx.from.id); throw error; } await ctx.reply(`✅ Получено ${item.stars_amount} Stars.`); } catch (error) { await ctx.reply(`⚠️ ${error.message}`); } });
|
||||
|
||||
bot.callbackQuery(/^admin:(.+)$/, async (ctx) => {
|
||||
await ctx.answerCallbackQuery(); if (!isOwner(config, ctx.from.id)) return; const action = ctx.match[1];
|
||||
if (action === "menu") return editOrReply(ctx, "🛡 <b>Админ-панель</b>", adminKeyboard());
|
||||
if (action === "stats") { const stats = db.stats(); return editOrReply(ctx, `📊 Пользователи: <b>${stats.users}</b>\nНомера: <b>${stats.numbers}</b>\nПродажи: <b>${stats.sales}</b>`, backKeyboard("admin:menu")); }
|
||||
if (action === "sales") { const lines = db.recentSales().map((sale) => `${sale.id}. ${escapeHTML(sale.product)} → <code>${sale.recipient_id}</code> · ${sale.stars_price}⭐`).join("\n"); return editOrReply(ctx, `📈 <b>Последние продажи</b>\n\n${lines || "—"}`, backKeyboard("admin:menu")); }
|
||||
const prompts = {
|
||||
broadcast: "Введите текст рассылки.",
|
||||
stars: `Формат: ${config.productName.toUpperCase()}_ID AMOUNT`,
|
||||
premium: `Формат: ${config.productName.toUpperCase()}_ID MONTHS`,
|
||||
promo: "Формат: CODE STARS LIMIT",
|
||||
giveaway: "Формат: STARS LIMIT Текст акции",
|
||||
bonus: "Формат: TELEGRAM_ID AMOUNT",
|
||||
invoice: "Формат: TELEGRAM_ID STARS Название",
|
||||
access: "Формат: PHONE TELEGRAM_ID",
|
||||
refund: "Отправьте transaction ID платежа Telegram Stars.",
|
||||
reply: "Формат: TICKET_ID текст ответа",
|
||||
rate: "Введите новый курс: сколько server Stars за 1 Telegram Star.",
|
||||
};
|
||||
if (prompts[action]) { db.setPending(ctx.from.id, `admin_${action}`, { operationID: `admin:${ctx.from.id}:${Date.now()}:${randomInt(1_000_000)}` }); return editOrReply(ctx, prompts[action], backKeyboard("admin:menu")); }
|
||||
});
|
||||
|
||||
bot.on("message:text", async (ctx) => {
|
||||
if (ctx.message.text.startsWith("/")) return; const pending = db.pending(ctx.from.id); if (!pending) return;
|
||||
const input = ctx.message.text.trim();
|
||||
try {
|
||||
if (pending.kind === "account") { const id = Number(input); if (!Number.isSafeInteger(id) || id <= 0) throw new Error("invalid ID"); db.setServerUserID(ctx.from.id, id); db.clearPending(ctx.from.id); return ctx.reply(`✅ ${config.productName} ID: ${id}`, { reply_markup: mainKeyboard(isOwner(config, ctx.from.id)) }); }
|
||||
if (pending.kind === "stars_amount") { const stars = Number(input); if (!Number.isSafeInteger(stars) || stars <= 0 || stars > 99999) throw new Error("amount must be from 1 to 99999"); const product = findProduct(`stars_${stars}`, db.starsRate()); db.clearPending(ctx.from.id); return ctx.reply(productText(product), { parse_mode: "HTML", reply_markup: productKeyboard(product, db, ctx.from.id) }); }
|
||||
if (pending.kind === "target") { const id = Number(input); if (!Number.isSafeInteger(id) || id <= 0) throw new Error("invalid ID"); const product = findProduct(pending.payload.productCode, db.starsRate()); if (!product) throw new Error("product not found"); db.rememberRecipient(ctx.from.id, id); db.clearPending(ctx.from.id); if (product.kind === KINDS.username) { db.setPending(ctx.from.id, "username", { productCode: product.code, targetID: id }); return ctx.reply("Введите желаемый username без @:"); } if (isOwner(config, ctx.from.id)) return fulfill(product, id, ctx.from, ctx.chat.id, `owner-${Date.now()}`); await sendInvoice(ctx, product, id); return; }
|
||||
if (pending.kind === "username") { const username = normalizeUsername(input); if (!username) throw new Error("username must be 5-32 latin characters and start with a letter"); const product = findProduct(pending.payload.productCode, db.starsRate()); db.clearPending(ctx.from.id); if (isOwner(config, ctx.from.id)) return fulfill(product, pending.payload.targetID, ctx.from, ctx.chat.id, `owner-${Date.now()}`, username); await sendInvoice(ctx, product, pending.payload.targetID, username); return; }
|
||||
if (pending.kind === "support") { const ticket = db.addSupportMessage(ctx.from.id, ctx.chat.id, input); db.clearPending(ctx.from.id); for (const owner of config.ownerIDs) await bot.api.sendMessage(owner, `💬 Тикет #${ticket}\nОт: ${escapeHTML(userName(ctx.from))} (<code>${ctx.from.id}</code>)\n\n${escapeHTML(input)}`, { parse_mode: "HTML" }); return ctx.reply(`✅ Обращение #${ticket} отправлено.`); }
|
||||
if (!isOwner(config, ctx.from.id)) return;
|
||||
if (pending.kind === "admin_broadcast") { db.clearPending(ctx.from.id); let ok = 0, failed = 0; for (const user of db.users()) { try { await bot.api.sendMessage(user.chat_id, input, { parse_mode: "HTML" }); ok++; } catch { failed++; } } return ctx.reply(`Рассылка завершена: ${ok} / ошибок ${failed}`); }
|
||||
if (pending.kind === "admin_stars") { const [id, amount] = input.split(/\s+/).map(Number); if (!Number.isSafeInteger(id) || id <= 0 || !Number.isSafeInteger(amount) || amount <= 0) throw new Error(`invalid ${config.productName} ID or amount`); await gramsrv.grantStars(id, amount, "Telegram bot administrator grant", pending.payload.operationID); db.clearPending(ctx.from.id); return ctx.reply(`✅ Выдано ${amount} Stars → ${config.productName} ID ${id}`); }
|
||||
if (pending.kind === "admin_premium") { const [id, months] = input.split(/\s+/).map(Number); if (!Number.isSafeInteger(id) || id <= 0 || !Number.isSafeInteger(months) || months <= 0) throw new Error(`invalid ${config.productName} ID or months`); await gramsrv.grantPremium(id, months, "Telegram bot administrator grant", pending.payload.operationID); db.clearPending(ctx.from.id); return ctx.reply(`✅ Premium на ${months} мес. → ${config.productName} ID ${id}`); }
|
||||
if (pending.kind === "admin_promo") { const [code, stars, limit] = input.split(/\s+/); db.createPromo(code, Number(stars), Number(limit)); db.clearPending(ctx.from.id); return ctx.reply(`✅ Промокод ${code} создан.`); }
|
||||
if (pending.kind === "admin_giveaway") { const [stars, limit, ...words] = input.split(/\s+/); const item = db.createGiveaway(words.join(" "), Number(stars), Number(limit)); db.clearPending(ctx.from.id); return ctx.reply(`🎁 ${escapeHTML(item.text)}`, { parse_mode: "HTML", reply_markup: new InlineKeyboard().text("Забрать награду", `giveaway:${item.id}`) }); }
|
||||
if (pending.kind === "admin_bonus") { const [id, amount] = input.split(/\s+/).map(Number); const balance = db.addBonus(id, amount); db.clearPending(ctx.from.id); return ctx.reply(`✅ Баланс ${id}: ${balance}`); }
|
||||
if (pending.kind === "admin_invoice") { const [idRaw, starsRaw, ...words] = input.split(/\s+/); const id = Number(idRaw), stars = Number(starsRaw), title = words.join(" "); if (!id || !stars || !title) throw new Error("invalid invoice"); await bot.api.sendInvoice(id, title, `Счёт: ${title}`, `custom|${Buffer.from(title).toString("base64url")}`, "XTR", [{ label: title, amount: stars }]); db.clearPending(ctx.from.id); return ctx.reply("✅ Счёт отправлен."); }
|
||||
if (pending.kind === "admin_access") { const [phone, telegramRaw] = input.split(/\s+/); const telegramID = Number(telegramRaw); if (!phone || !Number.isSafeInteger(telegramID) || telegramID <= 0) throw new Error("invalid phone or Telegram ID"); db.grantCodeAccess(phone, telegramID); db.clearPending(ctx.from.id); return ctx.reply(`✅ Доступ к кодам ${escapeHTML(phone)} выдан Telegram ID ${telegramID}.`, { parse_mode: "HTML" }); }
|
||||
if (pending.kind === "admin_refund") { const chargeID = input.trim(); const sale = db.saleByCharge(chargeID); if (!sale) throw new Error("sale not found for this transaction ID"); if (db.isRefunded(chargeID)) throw new Error("payment was already refunded"); await bot.api.refundStarPayment(sale.buyer_id, chargeID); db.markRefunded(chargeID, sale.buyer_id); db.clearPending(ctx.from.id); await bot.api.sendMessage(sale.buyer_id, `↩️ Оплата Telegram Stars возвращена.\n\nЧек: <code>${escapeHTML(chargeID)}</code>`, { parse_mode: "HTML" }).catch(() => {}); return ctx.reply("✅ Возврат выполнен."); }
|
||||
if (pending.kind === "admin_reply") { const [ticketRaw, ...words] = input.split(/\s+/); const ticketID = Number(ticketRaw), answer = words.join(" "); const ticket = db.supportMessage(ticketID); if (!ticket || !answer) throw new Error("ticket not found or reply is empty"); await bot.api.sendMessage(ticket.chat_id, `💬 <b>Ответ поддержки по обращению #${ticketID}</b>\n\n${escapeHTML(answer)}`, { parse_mode: "HTML" }); db.closeSupportMessage(ticketID); db.clearPending(ctx.from.id); return ctx.reply(`✅ Ответ по обращению #${ticketID} отправлен.`); }
|
||||
if (pending.kind === "admin_rate") { const rate = Number(input); if (!Number.isSafeInteger(rate) || rate <= 0) throw new Error("invalid rate"); db.setSetting("stars_rate", rate); db.clearPending(ctx.from.id); return ctx.reply(`✅ Курс: 1⭐ = ${rate} Stars`); }
|
||||
} catch (error) { await ctx.reply(`⚠️ ${escapeHTML(error.message)}`, { parse_mode: "HTML" }); }
|
||||
});
|
||||
|
||||
bot.catch(({ error, ctx }) => {
|
||||
if (error instanceof GrammyError) console.error("Telegram API error", error.description);
|
||||
else if (error instanceof HttpError) console.error("Telegram network error", error);
|
||||
else console.error(`Bot update ${ctx.update.update_id} failed`, error);
|
||||
});
|
||||
return bot;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
export const KINDS = Object.freeze({ premium: "premium", stars: "stars", number: "number", username: "username" });
|
||||
|
||||
const fixed = Object.freeze([
|
||||
{ kind: KINDS.premium, code: "premium_1m", title: "Premium — 1 month", description: "Premium subscription for one month", starsPrice: 20, months: 1 },
|
||||
{ kind: KINDS.premium, code: "premium_3m", title: "Premium — 3 months", description: "Premium subscription for three months", starsPrice: 40, months: 3 },
|
||||
{ kind: KINDS.number, code: "num_short", title: "Anonymous +888 8 XXX", description: "Short collectible anonymous number", starsPrice: 50, numberFormat: "short" },
|
||||
{ kind: KINDS.number, code: "num_long", title: "Anonymous +888 0XXX XXXX", description: "Anonymous +888 number", starsPrice: 25, numberFormat: "long" },
|
||||
{ kind: KINDS.username, code: "uname_10", title: "Collectible username — 10 TON", description: "Mint a collectible username", starsPrice: 10, bid: 10 },
|
||||
{ kind: KINDS.username, code: "uname_100", title: "Collectible username — 100 TON", description: "Mint a collectible username", starsPrice: 20, bid: 100 },
|
||||
{ kind: KINDS.username, code: "uname_1000", title: "Collectible username — 1000 TON", description: "Mint a collectible username", starsPrice: 40, bid: 1000 },
|
||||
]);
|
||||
|
||||
export function catalog(starsRate = 20) {
|
||||
const starPackages = [1, 5, 10, 25, 50, 100].map((price) => ({
|
||||
kind: KINDS.stars,
|
||||
code: `stars_${price}`,
|
||||
title: `${price * starsRate} Stars`,
|
||||
description: `${price * starsRate} server Stars for ${price} Telegram Stars`,
|
||||
starsPrice: price,
|
||||
starsAmount: price * starsRate,
|
||||
}));
|
||||
return [...fixed, ...starPackages];
|
||||
}
|
||||
|
||||
export function findProduct(code, starsRate = 20) {
|
||||
const fixedProduct = catalog(starsRate).find((product) => product.code === code);
|
||||
if (fixedProduct) return fixedProduct;
|
||||
const match = String(code).match(/^stars_([1-9]\d{0,4})$/);
|
||||
if (!match) return null;
|
||||
const starsPrice = Number(match[1]);
|
||||
return {
|
||||
kind: KINDS.stars,
|
||||
code: `stars_${starsPrice}`,
|
||||
title: `${starsPrice * starsRate} Stars`,
|
||||
description: `${starsPrice * starsRate} server Stars for ${starsPrice} Telegram Stars`,
|
||||
starsPrice,
|
||||
starsAmount: starsPrice * starsRate,
|
||||
};
|
||||
}
|
||||
|
||||
export function productsOfKind(kind, starsRate = 20) {
|
||||
return catalog(starsRate).filter((product) => product.kind === kind);
|
||||
}
|
||||
|
||||
export function normalizeUsername(value) {
|
||||
const username = String(value ?? "").trim().replace(/^@/, "").toLowerCase();
|
||||
return /^[a-z][a-z0-9_]{4,31}$/.test(username) ? username : "";
|
||||
}
|
||||
|
||||
export function buildPayload(productCode, targetUserID = 0, extra = "") {
|
||||
const encoded = Buffer.from(extra, "utf8").toString("base64url");
|
||||
return `store|${productCode}|${targetUserID}|${encoded}`;
|
||||
}
|
||||
|
||||
export function parsePayload(payload) {
|
||||
const [scope, code, target, encoded = ""] = String(payload).split("|", 4);
|
||||
const targetUserID = Number(target);
|
||||
if (scope !== "store" || !code || !Number.isSafeInteger(targetUserID) || targetUserID < 0) throw new Error("invalid invoice payload");
|
||||
return { code, targetUserID, extra: Buffer.from(encoded, "base64url").toString("utf8") };
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import "dotenv/config";
|
||||
import path from "node:path";
|
||||
|
||||
function required(name) {
|
||||
const value = (process.env[name] ?? "").trim();
|
||||
if (!value) throw new Error(`${name} is required`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function integer(name, fallback, { min = Number.MIN_SAFE_INTEGER } = {}) {
|
||||
const raw = (process.env[name] ?? "").trim();
|
||||
const value = raw ? Number(raw) : fallback;
|
||||
if (!Number.isSafeInteger(value) || value < min) throw new Error(`${name} must be an integer >= ${min}`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function ownerIDs() {
|
||||
const ids = new Set();
|
||||
for (const raw of required("OWNER_IDS").split(",")) {
|
||||
const id = Number(raw.trim());
|
||||
if (!Number.isSafeInteger(id) || id <= 0) throw new Error("OWNER_IDS contains an invalid Telegram user ID");
|
||||
ids.add(id);
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
export function loadConfig() {
|
||||
const webhookSecret = required("CODE_WEBHOOK_SECRET");
|
||||
if (webhookSecret.length < 24) throw new Error("CODE_WEBHOOK_SECRET must contain at least 24 characters");
|
||||
return Object.freeze({
|
||||
botToken: required("BOT_TOKEN"),
|
||||
productName: (process.env.PRODUCT_NAME ?? "Telesrv").trim() || "Telesrv",
|
||||
ownerIDs: ownerIDs(),
|
||||
publicUsername: (process.env.BOT_PUBLIC_USERNAME ?? "").replace(/^@/, "").trim(),
|
||||
gramsrvAPI: (process.env.GRAMSRV_API ?? "http://127.0.0.1:2399").replace(/\/+$/, ""),
|
||||
gramsrvToken: required("GRAMSRV_TOKEN"),
|
||||
gramsrvActor: (process.env.GRAMSRV_ACTOR ?? "telesrv-grammy-bot").trim(),
|
||||
publicBaseURL: (process.env.PUBLIC_BASE_URL ?? "https://example.com").replace(/\/+$/, ""),
|
||||
dbPath: path.resolve(process.env.BOT_DB_PATH ?? "./data/bot.sqlite3"),
|
||||
codeHost: (process.env.CODE_HTTP_HOST ?? "127.0.0.1").trim(),
|
||||
codePort: integer("CODE_HTTP_PORT", 2800, { min: 1 }),
|
||||
codeWebhookSecret: webhookSecret,
|
||||
requiredChannel: (process.env.REQUIRED_CHANNEL ?? "").trim(),
|
||||
requiredChannelURL: (process.env.REQUIRED_CHANNEL_URL ?? "").trim(),
|
||||
supportUsername: (process.env.SUPPORT_USERNAME ?? "").replace(/^@/, "").trim(),
|
||||
defaultLanguage: (process.env.DEFAULT_LANGUAGE ?? "ru").toLowerCase() === "en" ? "en" : "ru",
|
||||
defaultNumberCountry: (process.env.DEFAULT_NUMBER_COUNTRY ?? "RU").toUpperCase() === "US" ? "US" : "RU",
|
||||
referralBonus: integer("REFERRAL_BONUS", 100, { min: 0 }),
|
||||
dailyBonus: integer("DAILY_BONUS", 15, { min: 0 }),
|
||||
notificationTTLDays: integer("NOTIFICATION_TTL_DAYS", 30, { min: 1 }),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
import { mkdirSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { randomInt, randomBytes } from "node:crypto";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
|
||||
const RU_CODES = ["900", "902", "903", "904", "905", "906", "908", "909", "910", "911", "912", "913", "914", "915", "916", "917", "918", "919", "920", "921", "922", "923", "925", "926", "927", "928", "929", "930", "931", "932", "933", "937", "938", "939", "950", "951", "952", "953", "960", "961", "962", "963", "964", "965", "966", "967", "968", "969", "980", "981", "982", "983", "984", "985", "986", "987", "988", "989", "999"];
|
||||
const US_CODES = ["212", "213", "214", "215", "224", "281", "305", "310", "312", "313", "323", "347", "404", "407", "408", "410", "412", "415", "425", "469", "501", "503", "504", "505", "512", "513", "516", "561", "602", "603", "605", "612", "614", "615", "617", "619", "623", "702", "703", "704", "706", "708", "713", "714", "718", "720", "801", "802", "804", "805", "808", "813", "815", "816", "818", "901", "903", "904", "907", "909", "913", "914", "916", "917", "919"];
|
||||
|
||||
function now() { return Math.floor(Date.now() / 1000); }
|
||||
function dayKey(date = new Date()) { return date.toISOString().slice(0, 10); }
|
||||
function weekKey(date = new Date()) {
|
||||
const value = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
|
||||
value.setUTCDate(value.getUTCDate() + 4 - (value.getUTCDay() || 7));
|
||||
const start = new Date(Date.UTC(value.getUTCFullYear(), 0, 1));
|
||||
return `${value.getUTCFullYear()}-W${String(Math.ceil((((value - start) / 86400000) + 1) / 7)).padStart(2, "0")}`;
|
||||
}
|
||||
function pick(values) { return values[randomInt(values.length)]; }
|
||||
function digits(count) { return Array.from({ length: count }, () => randomInt(10)).join(""); }
|
||||
function normalizePhone(value) { const raw = String(value ?? "").replace(/[\s()\-]/g, ""); return raw && !raw.startsWith("+") ? `+${raw}` : raw; }
|
||||
|
||||
function generatedNumber(format, country) {
|
||||
if (format === "short") {
|
||||
const tail = digits(3); return { phone: `+8888${tail}`, display: `+888 8 ${tail}`, country: "ANON" };
|
||||
}
|
||||
if (format === "long") {
|
||||
const tail = digits(7); return { phone: `+8880${tail}`, display: `+888 0${tail.slice(0, 3)} ${tail.slice(3)}`, country: "ANON" };
|
||||
}
|
||||
if (country === "US") {
|
||||
const area = pick(US_CODES); const exchange = `${randomInt(2, 10)}${digits(2)}`; const line = digits(4);
|
||||
return { phone: `+1${area}${exchange}${line}`, display: `+1 (${area}) ${exchange}-${line}`, country: "US" };
|
||||
}
|
||||
const code = pick(RU_CODES); const tail = digits(7);
|
||||
return { phone: `+7${code}${tail}`, display: `+7 ${code} ${tail.slice(0, 3)}-${tail.slice(3, 5)}-${tail.slice(5)}`, country: "RU" };
|
||||
}
|
||||
|
||||
export class BotDatabase {
|
||||
constructor(filename) {
|
||||
mkdirSync(path.dirname(filename), { recursive: true });
|
||||
this.db = new DatabaseSync(filename);
|
||||
this.db.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000");
|
||||
this.migrate();
|
||||
}
|
||||
|
||||
migrate() {
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
telegram_id INTEGER PRIMARY KEY, chat_id INTEGER NOT NULL, username TEXT NOT NULL DEFAULT '', first_name TEXT NOT NULL DEFAULT '', server_user_id INTEGER NOT NULL DEFAULT 0,
|
||||
language TEXT NOT NULL DEFAULT 'ru', notifications INTEGER NOT NULL DEFAULT 1, bonus INTEGER NOT NULL DEFAULT 0,
|
||||
referred_by INTEGER REFERENCES users(telegram_id), referral_count INTEGER NOT NULL DEFAULT 0, daily_day TEXT NOT NULL DEFAULT '',
|
||||
spin_day TEXT NOT NULL DEFAULT '', spin_day_count INTEGER NOT NULL DEFAULT 0, spin_week TEXT NOT NULL DEFAULT '', spin_week_count INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS numbers (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, phone TEXT NOT NULL UNIQUE, display TEXT NOT NULL, format TEXT NOT NULL, country TEXT NOT NULL,
|
||||
owner_id INTEGER NOT NULL REFERENCES users(telegram_id), chat_id INTEGER NOT NULL, is_current INTEGER NOT NULL DEFAULT 1,
|
||||
login_code TEXT NOT NULL DEFAULT '', code_expires_at INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS numbers_current_owner_idx ON numbers(owner_id) WHERE is_current=1;
|
||||
CREATE TABLE IF NOT EXISTS code_access (phone TEXT NOT NULL, telegram_id INTEGER NOT NULL, PRIMARY KEY(phone, telegram_id));
|
||||
CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS pending (telegram_id INTEGER PRIMARY KEY, kind TEXT NOT NULL, payload TEXT NOT NULL DEFAULT '{}', updated_at INTEGER NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS processed_payments (
|
||||
charge_id TEXT PRIMARY KEY, telegram_id INTEGER NOT NULL, invoice_payload TEXT NOT NULL, amount INTEGER NOT NULL,
|
||||
status TEXT NOT NULL, error TEXT NOT NULL DEFAULT '', updated_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS sales (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, created_at INTEGER NOT NULL, product TEXT NOT NULL, title TEXT NOT NULL,
|
||||
stars_price INTEGER NOT NULL, recipient_id INTEGER NOT NULL, buyer_id INTEGER NOT NULL, buyer_name TEXT NOT NULL DEFAULT '', charge_id TEXT NOT NULL UNIQUE
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS recent_recipients (
|
||||
buyer_id INTEGER NOT NULL, recipient_id INTEGER NOT NULL, used_at INTEGER NOT NULL, PRIMARY KEY(buyer_id, recipient_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS promos (
|
||||
code TEXT PRIMARY KEY, stars_amount INTEGER NOT NULL, max_acts INTEGER NOT NULL, activations INTEGER NOT NULL DEFAULT 0,
|
||||
active INTEGER NOT NULL DEFAULT 1, created_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS promo_claims (code TEXT NOT NULL REFERENCES promos(code), telegram_id INTEGER NOT NULL, claimed_at INTEGER NOT NULL, PRIMARY KEY(code, telegram_id));
|
||||
CREATE TABLE IF NOT EXISTS giveaways (
|
||||
id TEXT PRIMARY KEY, text TEXT NOT NULL, stars_amount INTEGER NOT NULL, max_acts INTEGER NOT NULL,
|
||||
activations INTEGER NOT NULL DEFAULT 0, active INTEGER NOT NULL DEFAULT 1, created_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS giveaway_claims (giveaway_id TEXT NOT NULL REFERENCES giveaways(id), telegram_id INTEGER NOT NULL, claimed_at INTEGER NOT NULL, PRIMARY KEY(giveaway_id, telegram_id));
|
||||
CREATE TABLE IF NOT EXISTS support_messages (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, telegram_id INTEGER NOT NULL, chat_id INTEGER NOT NULL, text TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'open', created_at INTEGER NOT NULL, answered_at INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS refunds (
|
||||
charge_id TEXT PRIMARY KEY, telegram_id INTEGER NOT NULL, refunded_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS spin_awards (
|
||||
telegram_id INTEGER NOT NULL, day TEXT NOT NULL, week TEXT NOT NULL, server_user_id INTEGER NOT NULL,
|
||||
prize INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'pending', created_at INTEGER NOT NULL,
|
||||
PRIMARY KEY(telegram_id, day)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS otp_deliveries (
|
||||
delivery_id TEXT PRIMARY KEY, fingerprint TEXT NOT NULL, recipient TEXT NOT NULL,
|
||||
code TEXT NOT NULL, expires_at INTEGER NOT NULL, accepted_at INTEGER NOT NULL
|
||||
);
|
||||
INSERT OR IGNORE INTO settings(key,value) VALUES('stars_rate','20');
|
||||
`);
|
||||
}
|
||||
|
||||
close() { this.db.close(); }
|
||||
tx(work) { this.db.exec("BEGIN IMMEDIATE"); try { const value = work(); this.db.exec("COMMIT"); return value; } catch (error) { this.db.exec("ROLLBACK"); throw error; } }
|
||||
|
||||
upsertUser(from, chatID, language = "ru", referrerID = 0, referralBonus = 0) {
|
||||
const timestamp = now();
|
||||
return this.tx(() => {
|
||||
const existing = this.db.prepare("SELECT * FROM users WHERE telegram_id=?").get(from.id);
|
||||
this.db.prepare(`INSERT INTO users(telegram_id,chat_id,username,first_name,language,created_at,updated_at)
|
||||
VALUES(?,?,?,?,?,?,?) ON CONFLICT(telegram_id) DO UPDATE SET chat_id=excluded.chat_id,username=excluded.username,first_name=excluded.first_name,updated_at=excluded.updated_at`)
|
||||
.run(from.id, chatID, from.username ?? "", from.first_name ?? "", language, timestamp, timestamp);
|
||||
if (!existing && referrerID > 0 && referrerID !== from.id) {
|
||||
const referrer = this.db.prepare("SELECT telegram_id FROM users WHERE telegram_id=?").get(referrerID);
|
||||
if (referrer) {
|
||||
this.db.prepare("UPDATE users SET referred_by=? WHERE telegram_id=? AND referred_by IS NULL").run(referrerID, from.id);
|
||||
this.db.prepare("UPDATE users SET referral_count=referral_count+1,bonus=bonus+?,updated_at=? WHERE telegram_id=?").run(referralBonus, timestamp, referrerID);
|
||||
}
|
||||
}
|
||||
return this.user(from.id);
|
||||
});
|
||||
}
|
||||
|
||||
user(id) { return this.db.prepare("SELECT * FROM users WHERE telegram_id=?").get(id) ?? null; }
|
||||
users() { return this.db.prepare("SELECT * FROM users ORDER BY created_at").all(); }
|
||||
stats() { return { users: this.db.prepare("SELECT count(*) n FROM users").get().n, numbers: this.db.prepare("SELECT count(*) n FROM numbers").get().n, sales: this.db.prepare("SELECT count(*) n FROM sales").get().n }; }
|
||||
setLanguage(id, language) { this.db.prepare("UPDATE users SET language=?,updated_at=? WHERE telegram_id=?").run(language, now(), id); }
|
||||
toggleNotifications(id) { this.db.prepare("UPDATE users SET notifications=1-notifications,updated_at=? WHERE telegram_id=?").run(now(), id); return Boolean(this.user(id)?.notifications); }
|
||||
setServerUserID(id, serverUserID) { this.db.prepare("UPDATE users SET server_user_id=?,updated_at=? WHERE telegram_id=?").run(serverUserID, now(), id); }
|
||||
addBonus(id, amount) { this.db.prepare("UPDATE users SET bonus=MAX(0,bonus+?),updated_at=? WHERE telegram_id=?").run(amount, now(), id); return this.user(id)?.bonus ?? 0; }
|
||||
|
||||
claimDaily(id, amount) {
|
||||
return this.tx(() => {
|
||||
const user = this.user(id); if (!user) throw new Error("user not found");
|
||||
const day = dayKey(); if (user.daily_day === day) return { claimed: false, balance: user.bonus };
|
||||
this.db.prepare("UPDATE users SET daily_day=?,bonus=bonus+?,updated_at=? WHERE telegram_id=?").run(day, amount, now(), id);
|
||||
return { claimed: true, balance: user.bonus + amount };
|
||||
});
|
||||
}
|
||||
|
||||
createNumber(ownerID, chatID, format = "free", country = "RU", replace = false) {
|
||||
return this.tx(() => {
|
||||
const current = this.currentNumber(ownerID);
|
||||
if (current && !replace) return current;
|
||||
if (replace) this.db.prepare("UPDATE numbers SET is_current=0 WHERE owner_id=? AND is_current=1").run(ownerID);
|
||||
for (let attempt = 0; attempt < 400; attempt++) {
|
||||
const generated = generatedNumber(format, country);
|
||||
const code = String(randomInt(10000, 100000));
|
||||
try {
|
||||
const result = this.db.prepare(`INSERT INTO numbers(phone,display,format,country,owner_id,chat_id,is_current,login_code,code_expires_at,created_at)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?)`).run(generated.phone, generated.display, format, generated.country, ownerID, chatID, 1, code, now() + 300, now());
|
||||
return this.db.prepare("SELECT * FROM numbers WHERE id=?").get(result.lastInsertRowid);
|
||||
} catch (error) { if (!String(error.message).includes("UNIQUE")) throw error; }
|
||||
}
|
||||
throw new Error("could not generate a unique number");
|
||||
});
|
||||
}
|
||||
|
||||
currentNumber(ownerID) { return this.db.prepare("SELECT * FROM numbers WHERE owner_id=? AND is_current=1").get(ownerID) ?? null; }
|
||||
numbers(ownerID) { return this.db.prepare("SELECT * FROM numbers WHERE owner_id=? ORDER BY id DESC").all(ownerID); }
|
||||
findNumber(phone) { return this.db.prepare("SELECT * FROM numbers WHERE phone=? ORDER BY is_current DESC,id DESC LIMIT 1").get(normalizePhone(phone)) ?? null; }
|
||||
updateLoginCode(phone, code, expiresAt = now() + 300) {
|
||||
phone = normalizePhone(phone);
|
||||
return this.tx(() => {
|
||||
this.db.prepare("UPDATE numbers SET login_code=?,code_expires_at=? WHERE phone=?").run(String(code), expiresAt, phone);
|
||||
const number = this.findNumber(phone);
|
||||
const access = this.db.prepare("SELECT u.chat_id FROM code_access a JOIN users u ON u.telegram_id=a.telegram_id WHERE a.phone=?").all(phone);
|
||||
const chatIDs = new Set(access.map((row) => row.chat_id)); if (number?.chat_id) chatIDs.add(number.chat_id);
|
||||
return { number, chatIDs: [...chatIDs] };
|
||||
});
|
||||
}
|
||||
acceptLoginCodeDelivery(deliveryID, fingerprint, phone, code, expiresAt) {
|
||||
phone = normalizePhone(phone);
|
||||
return this.tx(() => {
|
||||
const existing = this.db.prepare("SELECT * FROM otp_deliveries WHERE delivery_id=?").get(deliveryID);
|
||||
if (existing) {
|
||||
if (existing.fingerprint !== fingerprint) throw new Error("IDEMPOTENCY_CONFLICT");
|
||||
return { duplicate: true, number: this.findNumber(existing.recipient), chatIDs: [] };
|
||||
}
|
||||
this.db.prepare("INSERT INTO otp_deliveries(delivery_id,fingerprint,recipient,code,expires_at,accepted_at) VALUES(?,?,?,?,?,?)").run(deliveryID, fingerprint, phone, String(code), expiresAt, now());
|
||||
this.db.prepare("UPDATE numbers SET login_code=?,code_expires_at=? WHERE phone=?").run(String(code), expiresAt, phone);
|
||||
const number = this.findNumber(phone);
|
||||
const access = this.db.prepare("SELECT u.chat_id FROM code_access a JOIN users u ON u.telegram_id=a.telegram_id WHERE a.phone=?").all(phone);
|
||||
const chatIDs = new Set(access.map((row) => row.chat_id)); if (number?.chat_id) chatIDs.add(number.chat_id);
|
||||
return { duplicate: false, number, chatIDs: [...chatIDs] };
|
||||
});
|
||||
}
|
||||
grantCodeAccess(phone, telegramID) { this.db.prepare("INSERT OR IGNORE INTO code_access(phone,telegram_id) VALUES(?,?)").run(normalizePhone(phone), telegramID); }
|
||||
|
||||
getSetting(key, fallback = "") { return this.db.prepare("SELECT value FROM settings WHERE key=?").get(key)?.value ?? fallback; }
|
||||
setSetting(key, value) { this.db.prepare("INSERT INTO settings(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(key, String(value)); }
|
||||
starsRate() { const value = Number(this.getSetting("stars_rate", "20")); return Number.isSafeInteger(value) && value > 0 ? value : 20; }
|
||||
|
||||
setPending(id, kind, payload = {}) { this.db.prepare("INSERT INTO pending(telegram_id,kind,payload,updated_at) VALUES(?,?,?,?) ON CONFLICT(telegram_id) DO UPDATE SET kind=excluded.kind,payload=excluded.payload,updated_at=excluded.updated_at").run(id, kind, JSON.stringify(payload), now()); }
|
||||
pending(id) { const row = this.db.prepare("SELECT * FROM pending WHERE telegram_id=?").get(id); return row ? { kind: row.kind, payload: JSON.parse(row.payload) } : null; }
|
||||
clearPending(id) { this.db.prepare("DELETE FROM pending WHERE telegram_id=?").run(id); }
|
||||
|
||||
recentRecipients(buyerID) { return this.db.prepare("SELECT recipient_id FROM recent_recipients WHERE buyer_id=? ORDER BY used_at DESC LIMIT 3").all(buyerID).map((row) => row.recipient_id); }
|
||||
rememberRecipient(buyerID, recipientID) { this.db.prepare("INSERT INTO recent_recipients(buyer_id,recipient_id,used_at) VALUES(?,?,?) ON CONFLICT(buyer_id,recipient_id) DO UPDATE SET used_at=excluded.used_at").run(buyerID, recipientID, now()); }
|
||||
|
||||
reserveSpin(id, serverUserID, proposedPrize) {
|
||||
return this.tx(() => {
|
||||
const user = this.user(id); if (!user) throw new Error("user not found");
|
||||
const day = dayKey(), week = weekKey();
|
||||
const existing = this.db.prepare("SELECT * FROM spin_awards WHERE telegram_id=? AND day=?").get(id, day);
|
||||
if (existing) {
|
||||
if (existing.status === "done") throw new Error("daily spin limit reached");
|
||||
if (existing.server_user_id !== serverUserID) throw new Error("finish the pending spin with the original server account ID");
|
||||
return existing;
|
||||
}
|
||||
const dayCount = user.spin_day === day ? user.spin_day_count : 0;
|
||||
const weekCount = user.spin_week === week ? user.spin_week_count : 0;
|
||||
if (dayCount >= 1) throw new Error("daily spin limit reached");
|
||||
if (weekCount >= 5) throw new Error("weekly spin limit reached");
|
||||
this.db.prepare("UPDATE users SET spin_day=?,spin_day_count=?,spin_week=?,spin_week_count=?,updated_at=? WHERE telegram_id=?").run(day, dayCount + 1, week, weekCount + 1, now(), id);
|
||||
this.db.prepare("INSERT INTO spin_awards(telegram_id,day,week,server_user_id,prize,status,created_at) VALUES(?,?,?,?,?,'pending',?)").run(id, day, week, serverUserID, proposedPrize, now());
|
||||
return this.db.prepare("SELECT * FROM spin_awards WHERE telegram_id=? AND day=?").get(id, day);
|
||||
});
|
||||
}
|
||||
finishSpin(id, day) { this.db.prepare("UPDATE spin_awards SET status='done' WHERE telegram_id=? AND day=?").run(id, day); }
|
||||
|
||||
createPromo(code, stars, limit) { code = code.trim().toLowerCase(); this.db.prepare("INSERT INTO promos(code,stars_amount,max_acts,created_at) VALUES(?,?,?,?)").run(code, stars, limit, now()); return code; }
|
||||
claimPromo(code, id) { return this.claimCampaign("promo", code.trim().toLowerCase(), id); }
|
||||
createGiveaway(text, stars, limit) { const id = randomBytes(4).toString("hex"); this.db.prepare("INSERT INTO giveaways(id,text,stars_amount,max_acts,created_at) VALUES(?,?,?,?,?)").run(id, text, stars, limit, now()); return this.db.prepare("SELECT * FROM giveaways WHERE id=?").get(id); }
|
||||
claimGiveaway(id, telegramID) { return this.claimCampaign("giveaway", id, telegramID); }
|
||||
|
||||
releaseCampaignClaim(kind, key, telegramID) {
|
||||
const table = kind === "promo" ? "promos" : "giveaways";
|
||||
const claims = kind === "promo" ? "promo_claims" : "giveaway_claims";
|
||||
const keyColumn = kind === "promo" ? "code" : "giveaway_id";
|
||||
const itemKey = kind === "promo" ? "code" : "id";
|
||||
this.tx(() => {
|
||||
const removed = this.db.prepare(`DELETE FROM ${claims} WHERE ${keyColumn}=? AND telegram_id=?`).run(key, telegramID);
|
||||
if (removed.changes) this.db.prepare(`UPDATE ${table} SET activations=MAX(0,activations-1),active=1 WHERE ${itemKey}=?`).run(key);
|
||||
});
|
||||
}
|
||||
|
||||
claimCampaign(kind, key, telegramID) {
|
||||
const table = kind === "promo" ? "promos" : "giveaways";
|
||||
const claims = kind === "promo" ? "promo_claims" : "giveaway_claims";
|
||||
const keyColumn = kind === "promo" ? "code" : "giveaway_id";
|
||||
return this.tx(() => {
|
||||
const item = this.db.prepare(`SELECT * FROM ${table} WHERE ${kind === "promo" ? "code" : "id"}=?`).get(key);
|
||||
if (!item || !item.active) throw new Error("campaign is unavailable");
|
||||
if (item.max_acts > 0 && item.activations >= item.max_acts) throw new Error("campaign limit reached");
|
||||
if (this.db.prepare(`SELECT 1 FROM ${claims} WHERE ${keyColumn}=? AND telegram_id=?`).get(key, telegramID)) throw new Error("already claimed");
|
||||
this.db.prepare(`INSERT INTO ${claims}(${keyColumn},telegram_id,claimed_at) VALUES(?,?,?)`).run(key, telegramID, now());
|
||||
const active = item.max_acts <= 0 || item.activations + 1 < item.max_acts ? 1 : 0;
|
||||
this.db.prepare(`UPDATE ${table} SET activations=activations+1,active=? WHERE ${kind === "promo" ? "code" : "id"}=?`).run(active, key);
|
||||
return { ...item, activations: item.activations + 1, active, stars_amount: item.stars_amount };
|
||||
});
|
||||
}
|
||||
|
||||
beginPayment(chargeID, telegramID, payload, amount) {
|
||||
return this.tx(() => {
|
||||
const row = this.db.prepare("SELECT * FROM processed_payments WHERE charge_id=?").get(chargeID);
|
||||
if (row?.status === "done") return false;
|
||||
if (row?.status === "processing" && row.updated_at > now() - 300) return false;
|
||||
this.db.prepare(`INSERT INTO processed_payments(charge_id,telegram_id,invoice_payload,amount,status,updated_at) VALUES(?,?,?,?,?,?)
|
||||
ON CONFLICT(charge_id) DO UPDATE SET status='processing',error='',updated_at=excluded.updated_at`).run(chargeID, telegramID, payload, amount, "processing", now());
|
||||
return true;
|
||||
});
|
||||
}
|
||||
finishPayment(chargeID) { this.db.prepare("UPDATE processed_payments SET status='done',error='',updated_at=? WHERE charge_id=?").run(now(), chargeID); }
|
||||
failPayment(chargeID, error) { this.db.prepare("UPDATE processed_payments SET status='failed',error=?,updated_at=? WHERE charge_id=?").run(String(error).slice(0, 1000), now(), chargeID); }
|
||||
addSale(sale) { this.db.prepare(`INSERT OR IGNORE INTO sales(created_at,product,title,stars_price,recipient_id,buyer_id,buyer_name,charge_id) VALUES(?,?,?,?,?,?,?,?)`).run(now(), sale.product, sale.title, sale.starsPrice, sale.recipientID, sale.buyerID, sale.buyerName ?? "", sale.chargeID); }
|
||||
saleByCharge(chargeID) { return this.db.prepare("SELECT * FROM sales WHERE charge_id=?").get(chargeID) ?? null; }
|
||||
recentSales(limit = 20) { return this.db.prepare("SELECT * FROM sales ORDER BY id DESC LIMIT ?").all(limit); }
|
||||
isRefunded(chargeID) { return Boolean(this.db.prepare("SELECT 1 FROM refunds WHERE charge_id=?").get(chargeID)); }
|
||||
markRefunded(chargeID, telegramID) { this.db.prepare("INSERT OR IGNORE INTO refunds(charge_id,telegram_id,refunded_at) VALUES(?,?,?)").run(chargeID, telegramID, now()); }
|
||||
|
||||
addSupportMessage(id, chatID, text) { const result = this.db.prepare("INSERT INTO support_messages(telegram_id,chat_id,text,created_at) VALUES(?,?,?,?)").run(id, chatID, text, now()); return Number(result.lastInsertRowid); }
|
||||
supportMessage(ticketID) { return this.db.prepare("SELECT * FROM support_messages WHERE id=?").get(ticketID) ?? null; }
|
||||
closeSupportMessage(ticketID) { this.db.prepare("UPDATE support_messages SET status='answered',answered_at=? WHERE id=?").run(now(), ticketID); }
|
||||
}
|
||||
|
||||
export const internals = { generatedNumber, normalizePhone, dayKey, weekKey };
|
||||
@@ -0,0 +1,44 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
|
||||
export class GramsrvClient {
|
||||
constructor(config) { this.config = config; }
|
||||
|
||||
async post(route, payload) {
|
||||
const response = await fetch(`${this.config.gramsrvAPI}${route}`, {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${this.config.gramsrvToken}`, "content-type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
signal: AbortSignal.timeout(15_000),
|
||||
});
|
||||
const text = await response.text();
|
||||
if (!response.ok) throw new Error(`gramsrv ${route} ${response.status}: ${text.slice(0, 500)}`);
|
||||
return text ? JSON.parse(text) : {};
|
||||
}
|
||||
|
||||
command(reason, fields, idempotencyKey = "") {
|
||||
const digest = idempotencyKey ? createHash("sha256").update(idempotencyKey).digest("hex").slice(0, 40) : randomUUID();
|
||||
return { command_id: `bot-${digest}`, actor: this.config.gramsrvActor, reason, dry_run: false, ...fields };
|
||||
}
|
||||
|
||||
grantStars(userID, amount, reason = "Telegram bot purchase", idempotencyKey = "") {
|
||||
return this.post("/v1/accounts/grant-stars", this.command(reason, { user_id: userID, amount }, idempotencyKey));
|
||||
}
|
||||
|
||||
grantPremium(userID, months, reason = "Telegram bot purchase", idempotencyKey = "") {
|
||||
return this.post("/v1/accounts/grant-premium", this.command(reason, { user_id: userID, months }, idempotencyKey));
|
||||
}
|
||||
|
||||
mintUsername(userID, username, bidTON, idempotencyKey = "") {
|
||||
const amount = (BigInt(bidTON) * 1_000_000_000n).toString();
|
||||
return this.post("/v1/collectible-usernames/mint", this.command("Telegram bot purchase", {
|
||||
username,
|
||||
owner_user_id: String(userID),
|
||||
currency: "TON",
|
||||
amount,
|
||||
crypto_currency: "TON",
|
||||
crypto_amount: amount,
|
||||
url: `${this.config.publicBaseURL}/nft/username/${username}`,
|
||||
purchase_date: Math.floor(Date.now() / 1000),
|
||||
}, idempotencyKey));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import http from "node:http";
|
||||
import { loadConfig } from "./config.js";
|
||||
import { BotDatabase } from "./db.js";
|
||||
import { GramsrvClient } from "./gramsrv.js";
|
||||
import { createBot } from "./bot.js";
|
||||
import { parseTelesrvDelivery, verifyTelesrvSignature } from "./otp.js";
|
||||
|
||||
const config = loadConfig();
|
||||
const db = new BotDatabase(config.dbPath);
|
||||
const gramsrv = new GramsrvClient(config);
|
||||
const bot = createBot({ config, db, gramsrv });
|
||||
|
||||
function escapeHTML(value) { return String(value ?? "").replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">"); }
|
||||
function json(response, status, body) { response.writeHead(status, { "content-type": "application/json; charset=utf-8" }); response.end(JSON.stringify(body)); }
|
||||
|
||||
async function deliverLoginCode(recipient, code, chatIDs) {
|
||||
const message = `🔐 <b>Код входа ${escapeHTML(config.productName)}</b>\n\n📞 <code>${escapeHTML(recipient)}</code>\n🔑 <code>${escapeHTML(code)}</code>\n\nНикому не сообщайте этот код.`;
|
||||
let delivered = 0;
|
||||
for (const chatID of chatIDs) {
|
||||
try { await bot.api.sendMessage(chatID, message, { parse_mode: "HTML" }); delivered++; }
|
||||
catch (error) { console.error("OTP delivery failed", chatID, error); }
|
||||
}
|
||||
if (!delivered) for (const owner of config.ownerIDs) await bot.api.sendMessage(owner, `${message}\n\n⚠️ Номер не привязан.`, { parse_mode: "HTML" }).catch(() => {});
|
||||
}
|
||||
|
||||
const server = http.createServer((request, response) => {
|
||||
if (request.method === "GET" && request.url === "/healthz") return json(response, 200, { ok: true });
|
||||
if (request.method !== "POST" || !["/code", "/v1/otp/deliveries"].includes(request.url)) return json(response, 404, { error: "not found" });
|
||||
const chunks = []; let size = 0, tooLarge = false;
|
||||
request.on("data", (chunk) => { size += chunk.length; if (size > 16_384) tooLarge = true; else chunks.push(chunk); });
|
||||
request.on("end", () => {
|
||||
try {
|
||||
if (tooLarge) return json(response, 413, { accepted: false, error_code: "REQUEST_TOO_LARGE", retryable: false });
|
||||
const raw = Buffer.concat(chunks);
|
||||
if (!verifyTelesrvSignature(config.codeWebhookSecret, request.headers, raw)) return json(response, 401, { accepted: false, error_code: "SIGNATURE_INVALID", retryable: false });
|
||||
const { recipient, code, deliveryID, expiresAt, fingerprint } = parseTelesrvDelivery(raw, request.headers);
|
||||
const delivery = db.acceptLoginCodeDelivery(deliveryID, fingerprint, recipient, code, expiresAt);
|
||||
// Authentication must not depend on Telegram Bot API latency. Persist the
|
||||
// code, acknowledge gramsrv immediately, then fan it out asynchronously.
|
||||
json(response, 202, { accepted: true, message_id: `grammy:${deliveryID}` });
|
||||
if (!delivery.duplicate) void deliverLoginCode(recipient, code, delivery.chatIDs).catch((error) => console.error("OTP dispatch failed", error));
|
||||
} catch (error) {
|
||||
console.error("OTP webhook failed", error);
|
||||
const conflict = error.message === "IDEMPOTENCY_CONFLICT";
|
||||
return json(response, conflict ? 409 : 400, { accepted: false, error_code: conflict ? "IDEMPOTENCY_CONFLICT" : "JSON_INVALID", retryable: false });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
server.listen(config.codePort, config.codeHost, () => console.log(`OTP webhook listening on http://${config.codeHost}:${config.codePort}`));
|
||||
|
||||
const me = await bot.api.getMe();
|
||||
bot.botInfo = me;
|
||||
console.log(`Starting @${me.username}`);
|
||||
await bot.api.setMyCommands([
|
||||
{ command: "start", description: "Открыть главное меню" },
|
||||
{ command: "menu", description: "Главное меню" },
|
||||
{ command: "promo_code", description: "Активировать промокод" },
|
||||
]);
|
||||
|
||||
let stopping = false;
|
||||
async function shutdown(signal) {
|
||||
if (stopping) return; stopping = true; console.log(`Stopping on ${signal}`);
|
||||
bot.stop(); server.close(); db.close();
|
||||
}
|
||||
process.once("SIGINT", () => shutdown("SIGINT"));
|
||||
process.once("SIGTERM", () => shutdown("SIGTERM"));
|
||||
|
||||
await bot.start({ allowed_updates: ["message", "callback_query", "pre_checkout_query"], onStart: () => console.log("Bot polling started") });
|
||||
@@ -0,0 +1,26 @@
|
||||
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
|
||||
|
||||
function secureEqual(left, right) {
|
||||
const expected = Buffer.from(left); const actual = Buffer.from(right ?? "");
|
||||
return expected.length === actual.length && timingSafeEqual(expected, actual);
|
||||
}
|
||||
|
||||
export function verifyTelesrvSignature(secret, headers, raw, nowSeconds = Math.floor(Date.now() / 1000)) {
|
||||
const timestamp = String(headers["x-telesrv-timestamp"] ?? "");
|
||||
if (!/^\d{1,20}$/.test(timestamp)) return false;
|
||||
const unix = Number(timestamp);
|
||||
if (!Number.isSafeInteger(unix) || Math.abs(nowSeconds - unix) > 300) return false;
|
||||
const expected = `sha256=${createHmac("sha256", secret).update(timestamp).update(".").update(raw).digest("hex")}`;
|
||||
return secureEqual(expected, headers["x-telesrv-signature"]);
|
||||
}
|
||||
|
||||
export function parseTelesrvDelivery(raw, headers, nowSeconds = Math.floor(Date.now() / 1000)) {
|
||||
const payload = JSON.parse(raw.toString("utf8"));
|
||||
const recipient = String(payload.recipient ?? "").trim(), code = String(payload.code ?? "").trim();
|
||||
const deliveryID = String(payload.delivery_id ?? "").trim(), idempotencyKey = String(headers["idempotency-key"] ?? "");
|
||||
const expiresAt = Math.floor(Date.parse(String(payload.expires_at ?? "")) / 1000);
|
||||
if (payload.version !== "1" || deliveryID.length < 1 || deliveryID.length > 128 || deliveryID !== idempotencyKey ||
|
||||
!recipient || recipient.length > 512 || !/^[0-9A-Za-z_-]{1,32}$/.test(code) ||
|
||||
!Number.isSafeInteger(expiresAt) || expiresAt <= nowSeconds) throw new Error("REQUEST_INVALID");
|
||||
return { recipient, code, deliveryID, expiresAt, fingerprint: createHash("sha256").update(raw).digest("hex") };
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { buildPayload, findProduct, normalizeUsername, parsePayload } from "../src/catalog.js";
|
||||
|
||||
test("invoice payload round-trips unicode extras", () => {
|
||||
assert.deepEqual(parsePayload(buildPayload("uname_10", 123, "юзер_name")), { code: "uname_10", targetUserID: 123, extra: "юзер_name" });
|
||||
});
|
||||
|
||||
test("dynamic Stars products use configured rate", () => {
|
||||
assert.equal(findProduct("stars_25", 30).starsAmount, 750);
|
||||
});
|
||||
|
||||
test("arbitrary Stars invoices are bounded and use the configured rate", () => {
|
||||
assert.equal(findProduct("stars_37", 25).starsAmount, 925);
|
||||
assert.equal(findProduct("stars_100000", 25), null);
|
||||
assert.equal(findProduct("stars_0", 25), null);
|
||||
});
|
||||
|
||||
test("collectible username validation is canonical", () => {
|
||||
assert.equal(normalizeUsername(" @Valid_Name "), "valid_name");
|
||||
assert.equal(normalizeUsername("1bad"), "");
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { BotDatabase } from "../src/db.js";
|
||||
|
||||
function fixture(t) {
|
||||
const dir = mkdtempSync(path.join(tmpdir(), "telesrv-grammy-")); const db = new BotDatabase(path.join(dir, "bot.sqlite3"));
|
||||
t.after(() => { db.close(); rmSync(dir, { recursive: true, force: true }); }); return db;
|
||||
}
|
||||
|
||||
test("start user receives persistent unique number and referral bonus is idempotent", (t) => {
|
||||
const db = fixture(t);
|
||||
db.upsertUser({ id: 1, username: "owner", first_name: "Owner" }, 1, "ru");
|
||||
db.upsertUser({ id: 2, username: "guest", first_name: "Guest" }, 2, "ru", 1, 100);
|
||||
db.upsertUser({ id: 2, username: "guest", first_name: "Guest" }, 2, "ru", 1, 100);
|
||||
const first = db.createNumber(2, 2, "free", "RU", false); const same = db.createNumber(2, 2, "free", "RU", false);
|
||||
assert.equal(first.id, same.id); assert.equal(db.user(1).bonus, 100); assert.equal(db.user(1).referral_count, 1);
|
||||
});
|
||||
|
||||
test("payment charge can finish only once and failed work can retry", (t) => {
|
||||
const db = fixture(t);
|
||||
assert.equal(db.beginPayment("charge", 1, "payload", 10), true); db.failPayment("charge", "temporary");
|
||||
assert.equal(db.beginPayment("charge", 1, "payload", 10), true); db.finishPayment("charge");
|
||||
assert.equal(db.beginPayment("charge", 1, "payload", 10), false);
|
||||
});
|
||||
|
||||
test("promo claims are transactionally unique", (t) => {
|
||||
const db = fixture(t); db.createPromo("HELLO", 50, 1);
|
||||
assert.equal(db.claimPromo("hello", 1).stars_amount, 50);
|
||||
assert.throws(() => db.claimPromo("hello", 1));
|
||||
});
|
||||
|
||||
test("code access, support replies, refunds and pending wheel awards are durable", (t) => {
|
||||
const db = fixture(t);
|
||||
db.upsertUser({ id: 1, first_name: "Owner" }, 10, "ru");
|
||||
db.upsertUser({ id: 2, first_name: "Viewer" }, 20, "ru");
|
||||
const number = db.createNumber(1, 10, "free", "RU", false);
|
||||
db.grantCodeAccess(number.phone, 2);
|
||||
const delivery = db.updateLoginCode(number.phone, "54321");
|
||||
assert.deepEqual(new Set(delivery.chatIDs), new Set([10, 20]));
|
||||
const accepted = db.acceptLoginCodeDelivery("otp-1", "hash-1", number.phone, "12345", 2_000_000_000);
|
||||
assert.deepEqual(new Set(accepted.chatIDs), new Set([10, 20]));
|
||||
assert.equal(db.acceptLoginCodeDelivery("otp-1", "hash-1", number.phone, "12345", 2_000_000_000).duplicate, true);
|
||||
assert.throws(() => db.acceptLoginCodeDelivery("otp-1", "different", number.phone, "12345", 2_000_000_000));
|
||||
|
||||
const ticket = db.addSupportMessage(1, 10, "help");
|
||||
assert.equal(db.supportMessage(ticket).status, "open");
|
||||
db.closeSupportMessage(ticket);
|
||||
assert.equal(db.supportMessage(ticket).status, "answered");
|
||||
|
||||
db.addSale({ product: "stars_1", title: "20 Stars", starsPrice: 1, recipientID: 100, buyerID: 1, buyerName: "Owner", chargeID: "charge-refund" });
|
||||
db.markRefunded("charge-refund", 1);
|
||||
assert.equal(db.isRefunded("charge-refund"), true);
|
||||
|
||||
const reserved = db.reserveSpin(1, 100, 50);
|
||||
assert.equal(db.reserveSpin(1, 100, 999).prize, 50);
|
||||
db.finishSpin(1, reserved.day);
|
||||
assert.throws(() => db.reserveSpin(1, 100, 50));
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { GramsrvClient } from "../src/gramsrv.js";
|
||||
|
||||
test("Admin API retries reuse a deterministic command id", () => {
|
||||
const client = new GramsrvClient({ gramsrvActor: "test" });
|
||||
const first = client.command("purchase", { user_id: 1 }, "payment:charge-1");
|
||||
const retry = client.command("purchase", { user_id: 1 }, "payment:charge-1");
|
||||
const other = client.command("purchase", { user_id: 1 }, "payment:charge-2");
|
||||
assert.equal(first.command_id, retry.command_id);
|
||||
assert.notEqual(first.command_id, other.command_id);
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import { migrateLegacy } from "../scripts/migrate-legacy-db.js";
|
||||
import { BotDatabase } from "../src/db.js";
|
||||
|
||||
test("legacy Python database is migrated without modifying the source", (t) => {
|
||||
const dir = mkdtempSync(path.join(tmpdir(), "telesrv-legacy-"));
|
||||
t.after(() => rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
|
||||
const source = path.join(dir, "old.sqlite3");
|
||||
const destination = path.join(dir, "new.sqlite3");
|
||||
const old = new DatabaseSync(source);
|
||||
old.exec(`
|
||||
CREATE TABLE users(tg_id INTEGER PRIMARY KEY,username TEXT,first_name TEXT,phone TEXT,latest_code TEXT,code_expires_at INTEGER,bonuses INTEGER,referrer_id INTEGER,referrals_count INTEGER,language TEXT,notifications INTEGER,is_admin INTEGER,state TEXT,created_at INTEGER,updated_at INTEGER,last_daily_at INTEGER,number_changed_at INTEGER);
|
||||
CREATE TABLE numbers(phone TEXT PRIMARY KEY,tg_id INTEGER,active INTEGER,created_at INTEGER,retired_at INTEGER);
|
||||
CREATE TABLE support_messages(id INTEGER PRIMARY KEY,tg_id INTEGER,text TEXT,status TEXT,created_at INTEGER);
|
||||
INSERT INTO users VALUES(10,'owner','Owner','+79990000001','12345',2000,70,NULL,1,'ru',1,1,'',100,200,86400,0);
|
||||
INSERT INTO users VALUES(11,'friend','Friend','+18880000001','54321',3000,5,10,0,'en',0,0,'',110,210,0,0);
|
||||
INSERT INTO numbers VALUES('+79990000001',10,1,100,NULL);
|
||||
INSERT INTO numbers VALUES('+18880000001',11,1,110,NULL);
|
||||
INSERT INTO support_messages VALUES(7,11,'help','open',120);
|
||||
`);
|
||||
old.close();
|
||||
const sourceBefore = readFileSync(source);
|
||||
|
||||
assert.deepEqual(migrateLegacy(source, destination), { users: 2, numbers: 2, supportMessages: 1 });
|
||||
const migrated = new BotDatabase(destination);
|
||||
assert.deepEqual(migrated.db.prepare("SELECT telegram_id,bonus,referred_by,language,notifications,daily_day FROM users ORDER BY telegram_id").all().map((row) => ({ ...row })), [
|
||||
{ telegram_id: 10, bonus: 70, referred_by: null, language: "ru", notifications: 1, daily_day: "1970-01-02" },
|
||||
{ telegram_id: 11, bonus: 5, referred_by: 10, language: "en", notifications: 0, daily_day: "" },
|
||||
]);
|
||||
assert.deepEqual(migrated.db.prepare("SELECT phone,owner_id,is_current,login_code FROM numbers ORDER BY owner_id").all().map((row) => ({ ...row })), [
|
||||
{ phone: "+79990000001", owner_id: 10, is_current: 1, login_code: "12345" },
|
||||
{ phone: "+18880000001", owner_id: 11, is_current: 1, login_code: "54321" },
|
||||
]);
|
||||
assert.equal(migrated.db.prepare("SELECT text FROM support_messages WHERE id=7").get().text, "help");
|
||||
migrated.close();
|
||||
assert.deepEqual(readFileSync(source), sourceBefore);
|
||||
assert.throws(() => migrateLegacy(source, destination), /destination already exists/);
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { createHmac } from "node:crypto";
|
||||
import { parseTelesrvDelivery, verifyTelesrvSignature } from "../src/otp.js";
|
||||
|
||||
test("OTP webhook verifies gramsrv v1 signatures and request envelopes", () => {
|
||||
const now = 1_800_000_000, secret = "a-long-test-webhook-secret";
|
||||
const payload = {
|
||||
version: "1", delivery_id: "delivery-1", purpose: "login_sms", channel: "sms",
|
||||
recipient: "+79991234567", code: "12345", expires_at: "2027-01-15T08:05:00Z", expires_in: 300,
|
||||
};
|
||||
const raw = Buffer.from(JSON.stringify(payload)), timestamp = String(now);
|
||||
const signature = `sha256=${createHmac("sha256", secret).update(timestamp).update(".").update(raw).digest("hex")}`;
|
||||
const headers = { "x-telesrv-timestamp": timestamp, "x-telesrv-signature": signature, "idempotency-key": "delivery-1" };
|
||||
assert.equal(verifyTelesrvSignature(secret, headers, raw, now), true);
|
||||
assert.equal(parseTelesrvDelivery(raw, headers, now).deliveryID, "delivery-1");
|
||||
assert.equal(verifyTelesrvSignature(secret, { ...headers, "x-telesrv-signature": "sha256=bad" }, raw, now), false);
|
||||
assert.equal(verifyTelesrvSignature(secret, headers, raw, now + 301), false);
|
||||
assert.throws(() => parseTelesrvDelivery(raw, { ...headers, "idempotency-key": "other" }, now));
|
||||
});
|
||||
Reference in New Issue
Block a user