diff --git a/.env.example b/.env.example index f6d2f69..c7e6ba3 100644 --- a/.env.example +++ b/.env.example @@ -1,37 +1,28 @@ UVICORN_HOST = "0.0.0.0" UVICORN_PORT = 8000 - -## We highly recommend add admin using `marzban cli` tool and do not use -## the following variables which is somehow hard codded infrmation. +## THE FOLLOWING TWO VARIABLES ARE NOT SUPPORTED ANYMORE, USE merzneshin cli. # SUDO_USERNAME = "admin" # SUDO_PASSWORD = "admin" # DASHBOARD_PATH = "/dashboard/" -# UVICORN_UDS: "/run/marzban.socket" -# UVICORN_SSL_CERTFILE = "/var/lib/marzban/certs/example.com/fullchain.pem" -# UVICORN_SSL_KEYFILE = "/var/lib/marzban/certs/example.com/key.pem" +# UVICORN_UDS: "/run/marzneshin.socket" +# UVICORN_SSL_CERTFILE = "/var/lib/marzneshin/certs/example.com/fullchain.pem" +# UVICORN_SSL_KEYFILE = "/var/lib/marzneshin/certs/example.com/key.pem" -# XRAY_JSON = "xray_config.json" -# XRAY_SUBSCRIPTION_URL_PREFIX = "https://example.com" -# XRAY_SUBSCRIPTION_PATH = sub -# XRAY_EXECUTABLE_PATH = "/usr/local/bin/xray" -# XRAY_ASSETS_PATH = "/usr/local/share/xray" -# XRAY_EXCLUDE_INBOUND_TAGS = "INBOUND_X INBOUND_Y" -# XRAY_FALLBACKS_INBOUND_TAG = "INBOUND_X" +# SUBSCRIPTION_URL_PREFIX = "https://example.com" # TELEGRAM_API_TOKEN = 123456789:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA # TELEGRAM_ADMIN_ID = 987654321, 123456789 # TELEGRAM_LOGGER_CHANNEL_ID = -1234567890123 -# TELEGRAM_DEFAULT_VLESS_FLOW = "xtls-rprx-vision" # TELEGRAM_PROXY_URL = "http://localhost:8080" # DISCORD_WEBHOOK_URL = "https://discord.com/api/webhooks/xxxxxxx" -# CUSTOM_TEMPLATES_DIRECTORY="/var/lib/marzban/templates/" +# CUSTOM_TEMPLATES_DIRECTORY="/var/lib/marzneshin/templates/" # CLASH_SUBSCRIPTION_TEMPLATE="clash/my-custom-template.yml" # SUBSCRIPTION_PAGE_TEMPLATE="subscription/index.html" # HOME_PAGE_TEMPLATE="home/index.html" diff --git a/README.md b/README.md index 244dc87..2dd050b 100755 --- a/README.md +++ b/README.md @@ -39,8 +39,8 @@ ## Table of Contents - [Overview](#overview) - - [Features](#features) - - [Supported Languages](#supported-languages) + - [Features](#features) + - [Supported Languages](#supported-languages) - [Installation guide](#installation-guide) - [Configuration](#configuration) - [API](#api) @@ -57,18 +57,18 @@ Marzneshin is a censorship circumvention tool utilizing other censorship circumvention tools. -Dashboard enables access to nodes(configurations, status and stats, logs), +Dashboard enables access to nodes(configurations, status and stats, logs), hosts, users, service entities; while providing monitoring and system statistics. -On the other hand, the backend manages nodes, users, users' subscriptions, etc. +On the other hand, the backend manages nodes, users, users' subscriptions, etc. -Marzneshin controls the [Marznodes](https://github.com/khodedawsh/marznode) +Marzneshin controls the [Marznodes](https://github.com/khodedawsh/marznode) connected to it; monitoring/disabling/enabling users on marznode instances while marznode manages and interacts with vpn backends (such as xray). ### Features -- **Web UI** Dashboard +- **Web UI** Dashboard - **Multi Nodes** support for traffic distribution, scalability, and fault tolerance - Supports protocols **Vmess**, **VLESS**, **Trojan** and **Shadowsocks** as provided by xray - **Multi-protocol** for a single user @@ -78,21 +78,22 @@ marznode manages and interacts with vpn backends (such as xray). - reset traffic periodically (daily, weekly,...) - **Subscription link** compatible with **V2ray** (e.g. V2RayNG, OneClick, Nekoray, etc.), **Clash** and **ClashMeta** - Automated **Share link** and **QRcode** generator -- System, nodes, traffic statistics, users monitoring +- System, nodes, traffic statistics, users monitoring - Integrated **Command Line Interface (CLI)** - **Multi-admin** support (WIP) - Marzneshin is decoupled from VPN backends - Resilient and fault tolerant node management - UI performance and redesign - Deployment and Developer Kit: + - REST-full API - Kubernetes and multiple deployment strategy and options (WIP) ### Supported Languages + - Russian (WIP) -- English +- English - Kurdish (Soranî, Kurmancî) - Persian (WIP) @@ -109,15 +110,18 @@ To install with mariadb: ```bash sudo bash -c "$(curl -sL https://github.com/khodedawsh/Marzneshin/raw/master/script.sh)" @ install --database mariadb ``` + You could also use mysql by writing mysql instead, however mariadb is **recommended**. Also to install the latest nightly release use the `--nightly` option. Once the installation is complete: - You'd notice the logs, which you could stop watching by pressing `Ctrl+C`; The process will continue running normally. -- the configuration file can be found at `/etc/opt/marzneshin/.env` (refer to [configurations](#configuration) section to see variables) +- the configuration file can be found at `/etc/opt/marzneshin/.env` (refer to [configurations](#configuration) section + to see variables) - Data files will be placed at `/var/lib/marzneshin`; e.g. the sqlite database. -- You can access the Marzneshin dashboard by opening a web browser and navigating to `http://:8000/dashboard/` +- You can access the Marzneshin dashboard by opening a web browser and navigating + to `http://:8000/dashboard/` Next, you need to create a sudo admin for logging into the Marzneshin dashboard by the following command @@ -162,7 +166,8 @@ Then run the following command to run the database migration scripts alembic upgrade head ``` -If you want to use `marzneshin-cli`, you should link it to a file in your `$PATH`, make it executable, and install the auto-completion: +If you want to use `marzneshin-cli`, you should link it to a file in your `$PATH`, make it executable, and install the +auto-completion: ```bash sudo ln -s $(pwd)/marzneshin-cli.py /usr/bin/marzneshin-cli @@ -254,7 +259,8 @@ server { } ``` -By default the app will be run on `http://localhost:8000/dashboard`. You can configure it using changing the `UVICORN_HOST` and `UVICORN_PORT` environment variables. +By default the app will be run on `http://localhost:8000/dashboard`. You can configure it using changing +the `UVICORN_HOST` and `UVICORN_PORT` environment variables. # Configuration @@ -262,16 +268,14 @@ By default the app will be run on `http://localhost:8000/dashboard`. You can con > You can set settings below using environment variables or placing them in `.env` file. | Variable | Description | -| --------------------------------- | ----------------------------------------------------------------------------------------------------- | -| SUDO_USERNAME | Superuser's username | -| SUDO_PASSWORD | Superuser's password | +|-----------------------------------|-------------------------------------------------------------------------------------------------------| | SQLALCHEMY_DATABASE_URL | Database URL ([SQLAlchemy's docs](https://docs.sqlalchemy.org/en/20/core/engines.html#database-urls)) | | UVICORN_HOST | Bind application to this host (default: `0.0.0.0`) | | UVICORN_PORT | Bind application to this port (default: `8000`) | | UVICORN_UDS | Bind application to a UNIX domain socket | | UVICORN_SSL_CERTFILE | SSL certificate file to have application on https | | UVICORN_SSL_KEYFILE | SSL key file to have application on https | -| XRAY_SUBSCRIPTION_URL_PREFIX | Prefix of subscription URLs | +| SUBSCRIPTION_URL_PREFIX | Prefix of subscription URLs | | CUSTOM_TEMPLATES_DIRECTORY | Customized templates directory (default: `app/templates`) | | CLASH_SUBSCRIPTION_TEMPLATE | The template that will be used for generating clash configs (default: `clash/default.yml`) | | SUBSCRIPTION_PAGE_TEMPLATE | The template used for generating subscription info page (default: `subscription/index.html`) | @@ -291,29 +295,42 @@ By default the app will be run on `http://localhost:8000/dashboard`. You can con # API -Marzneshin provides a REST API that enables developers to interact with Marzneshin services programmatically. To view the API documentation in Swagger UI or ReDoc, set the configuration variable `DOCS=True` and navigate to the `/docs` and `/redoc`. +Marzneshin provides a REST API that enables developers to interact with Marzneshin services programmatically. To view +the API documentation in Swagger UI or ReDoc, set the configuration variable `DOCS=True` and navigate to the `/docs` +and `/redoc`. # Backup -It's always a good idea to backup your Marzneshin files regularly to prevent data loss in case of system failures or accidental deletion. Here are the steps to backup Marzneshin: +It's always a good idea to backup your Marzneshin files regularly to prevent data loss in case of system failures or +accidental deletion. Here are the steps to backup Marzneshin: -1. By default, all Marzneshin important files are saved in `/var/lib/marzneshin` (Docker versions). Copy the entire `/var/lib/marzneshin` directory to a backup location of your choice, such as an external hard drive or cloud storage. -2. Additionally, make sure to backup your env file, which contains your configuration variables. If you installed Marzneshin using the script (recommended installation approach), the env and other configurations should be inside `/etc/opt/marzneshin/` directory. +1. By default, all Marzneshin important files are saved in `/var/lib/marzneshin` (Docker versions). Copy the + entire `/var/lib/marzneshin` directory to a backup location of your choice, such as an external hard drive or cloud + storage. +2. Additionally, make sure to backup your env file, which contains your configuration variables. If you installed + Marzneshin using the script (recommended installation approach), the env and other configurations should be + inside `/etc/opt/marzneshin/` directory. -By following these steps, you can ensure that you have a backup of all your Marzneshin files and data, as well as your configuration variables and Xray configuration, in case you need to restore them in the future. Remember to update your backups regularly to keep them up-to-date. +By following these steps, you can ensure that you have a backup of all your Marzneshin files and data, as well as your +configuration variables and Xray configuration, in case you need to restore them in the future. Remember to update your +backups regularly to keep them up-to-date. # Telegram Bot -Marzneshin comes with an integrated Telegram bot that can handle server management, user creation and removal, and send notifications. This bot can be easily enabled by following a few simple steps, and it provides a convenient way to interact with Marzneshin without having to log in to the server every time. +Marzneshin comes with an integrated Telegram bot that can handle server management, user creation and removal, and send +notifications. This bot can be easily enabled by following a few simple steps, and it provides a convenient way to +interact with Marzneshin without having to log in to the server every time. To enable Telegram Bot: 1. set `TELEGRAM_API_TOKEN` to your bot's API Token -2. set `TELEGRAM_ADMIN_ID` to your Telegram account's numeric ID, you can get your ID from [@userinfobot](https://t.me/userinfobot) +2. set `TELEGRAM_ADMIN_ID` to your Telegram account's numeric ID, you can get your ID + from [@userinfobot](https://t.me/userinfobot) # Marzneshin CLI -Marzneshin comes with an integrated CLI named `marzneshin-cli` which allows administrators to have direct interaction with it. +Marzneshin comes with an integrated CLI named `marzneshin-cli` which allows administrators to have direct interaction +with it. If you've installed Marzneshin using the installation script, you can access the cli commands by running @@ -331,7 +348,8 @@ For more information, You can read [Marzneshin CLI's documentation](./cli/README You can set a webhook address and Marzneshin will send the notifications to that address. -the requests will be sent as a post request to the adress provided by `WEBHOOK_ADDRESS` with `WEBHOOK_SECRET` as `x-webhook-secret` in the headers. +the requests will be sent as a post request to the adress provided by `WEBHOOK_ADDRESS` with `WEBHOOK_SECRET` +as `x-webhook-secret` in the headers. Example request sent from Marzneshin: @@ -352,11 +370,13 @@ Body: {"username": "marzneshin_test_user", "action": "user_updated", "enqueued_at": 1680506457.636369, "tries": 0} ``` -Different action typs are: `user_created`, `user_updated`, `user_deleted`, `user_limited`, `user_expired`, `user_disabled`, `user_enabled` +Different action typs +are: `user_created`, `user_updated`, `user_deleted`, `user_limited`, `user_expired`, `user_disabled`, `user_enabled` # Donation -If you found Marzneshin useful and would like to support its development, you can make a donation in one of the following crypto networks: +If you found Marzneshin useful and would like to support its development, you can make a donation in one of the +following crypto networks: - Bitcoin network: 13ZDhE5KHGsfjM4A22eLTUgW98WpXhQTuF - TRON network (TRC20): TYxFCiRqJ3SiV6rAQAmJUd3DgVmJvEAfz4 @@ -372,7 +392,9 @@ Published under [AGPL-3.0](./LICENSE). # Contributors -We ❤️‍🔥 contributors! If you'd like to contribute, please check out our [Contributing Guidelines](CONTRIBUTING.md) and feel free to submit a pull request or open an issue. We also welcome you to join our [Telegram](https://t.me/marzneshins) group for either support or contributing guidance. +We ❤️‍🔥 contributors! If you'd like to contribute, please check out our [Contributing Guidelines](CONTRIBUTING.md) and +feel free to submit a pull request or open an issue. We also welcome you to join +our [Telegram](https://t.me/marzneshins) group for either support or contributing guidance. Check [open issues](https://github.com/khodedawsh/marzneshin/issues) to help the progress of this project. diff --git a/app/dependencies.py b/app/dependencies.py index 3614106..83098e7 100644 --- a/app/dependencies.py +++ b/app/dependencies.py @@ -2,13 +2,11 @@ from datetime import datetime from typing import Annotated from fastapi import Depends, HTTPException, status -from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.orm import Session from app.db import crud, User, GetDB from app.models.admin import Admin, oauth2_scheme from app.utils.jwt import get_admin_payload -from config import SUDOERS def get_db(): # Dependency @@ -24,9 +22,6 @@ def get_admin( if not payload: return - if payload["username"] in SUDOERS and payload["is_sudo"] is True: - return Admin(username=payload["username"], is_sudo=True) - dbadmin = crud.get_admin(db, payload["username"]) if not dbadmin: return diff --git a/app/models/user.py b/app/models/user.py index 57e65f9..3f6ef82 100644 --- a/app/models/user.py +++ b/app/models/user.py @@ -13,7 +13,7 @@ from pydantic import ( model_validator, ) -from config import XRAY_SUBSCRIPTION_URL_PREFIX +from config import SUBSCRIPTION_URL_PREFIX USERNAME_REGEXP = r"^\w{3,32}$" @@ -106,10 +106,10 @@ class UserCreate(User): ) if self.expire: raise ValueError("User cannot be on hold with specified expire.") - elif self.status == UserStatusCreate.active and (self.on_hold_expire_duration or self.on_hold_timeout): - raise ValueError( - "on hold parametrs set when user status isn't on_hold." - ) + elif self.status == UserStatusCreate.active and ( + self.on_hold_expire_duration or self.on_hold_timeout + ): + raise ValueError("on hold parametrs set when user status isn't on_hold.") return self @field_validator("expire") @@ -186,7 +186,7 @@ class UserResponse(User): @property def subscription_url(self) -> str: salt = secrets.token_hex(8) - url_prefix = XRAY_SUBSCRIPTION_URL_PREFIX.replace("*", salt) + url_prefix = SUBSCRIPTION_URL_PREFIX.replace("*", salt) return f"{url_prefix}/sub/{self.username}/{self.key}" diff --git a/app/routes/admin.py b/app/routes/admin.py index a613e7b..aa78d6b 100644 --- a/app/routes/admin.py +++ b/app/routes/admin.py @@ -12,18 +12,10 @@ from app.db.models import Admin as DBAdmin from app.dependencies import AdminDep, SudoAdminDep, DBDep from app.models.admin import Admin, AdminCreate, AdminInDB, AdminModify, Token from app.utils.jwt import create_admin_token -from config import SUDOERS router = APIRouter(tags=["Admin"], prefix="/admins") -def authenticate_env_sudo(username: str, password: str) -> bool: - try: - return password == SUDOERS[username] - except KeyError: - return False - - def authenticate_admin(db: Session, username: str, password: str) -> Optional[Admin]: dbadmin = crud.get_admin(db, username) if not dbadmin: @@ -60,9 +52,6 @@ def get_current_admin(admin: AdminDep): @router.post("/token", response_model=Token) def admin_token(form_data: Annotated[OAuth2PasswordRequestForm, Depends()], db: DBDep): - if authenticate_env_sudo(form_data.username, form_data.password): - return Token(access_token=create_admin_token(form_data.username, is_sudo=True)) - if dbadmin := authenticate_admin(db, form_data.username, form_data.password): return Token( access_token=create_admin_token(form_data.username, is_sudo=dbadmin.is_sudo) diff --git a/app/utils/jwt.py b/app/utils/jwt.py index 0971433..09e882d 100644 --- a/app/utils/jwt.py +++ b/app/utils/jwt.py @@ -4,8 +4,8 @@ from typing import Union from jose import JWTError, jwt -from config import JWT_ACCESS_TOKEN_EXPIRE_MINUTES, SUDOERS from app.db import GetDB, get_jwt_secret_key +from config import JWT_ACCESS_TOKEN_EXPIRE_MINUTES @lru_cache(maxsize=None) diff --git a/config.py b/config.py index 33ebacb..900df56 100755 --- a/config.py +++ b/config.py @@ -1,4 +1,3 @@ -import os from decouple import config from dotenv import load_dotenv @@ -27,12 +26,7 @@ VITE_BASE_API = ( else config("VITE_BASE_API", default="/api/") ) -XRAY_FALLBACKS_INBOUND_TAG = config( - "XRAY_FALLBACKS_INBOUND_TAG", cast=str, default="" -) or config("XRAY_FALLBACK_INBOUND_TAG", cast=str, default="") -XRAY_SUBSCRIPTION_URL_PREFIX = config("XRAY_SUBSCRIPTION_URL_PREFIX", default="").strip( - "/" -) +SUBSCRIPTION_URL_PREFIX = config("SUBSCRIPTION_URL_PREFIX", default="").strip("/") TELEGRAM_API_TOKEN = config("TELEGRAM_API_TOKEN", default="") TELEGRAM_ADMIN_ID = config( @@ -44,7 +38,6 @@ TELEGRAM_ADMIN_ID = config( ) TELEGRAM_PROXY_URL = config("TELEGRAM_PROXY_URL", default="") TELEGRAM_LOGGER_CHANNEL_ID = config("TELEGRAM_LOGGER_CHANNEL_ID", cast=int, default=0) -TELEGRAM_DEFAULT_VLESS_FLOW = config("TELEGRAM_DEFAULT_VLESS_FLOW", default="") JWT_ACCESS_TOKEN_EXPIRE_MINUTES = config( "JWT_ACCESS_TOKEN_EXPIRE_MINUTES", cast=int, default=1440 @@ -64,14 +57,6 @@ SINGBOX_SUBSCRIPTION_TEMPLATE = config( ) -# USERNAME: PASSWORD -SUDOERS = ( - {config("SUDO_USERNAME"): config("SUDO_PASSWORD")} - if config("SUDO_USERNAME", default="") and config("SUDO_PASSWORD", default="") - else {} -) - - WEBHOOK_ADDRESS = config("WEBHOOK_ADDRESS", default=None) WEBHOOK_SECRET = config("WEBHOOK_SECRET", default=None)