"""Automatic Dhan authentication using the supported PIN/TOTP token endpoint.""" from __future__ import annotations import json import math import os import re import tempfile import threading import time from contextlib import contextmanager from datetime import datetime, timedelta, timezone import pyotp import requests from cryptography.fernet import Fernet, InvalidToken IST = timezone(timedelta(hours=5, minutes=30)) _AUTH_URL = "https://auth.dhan.co/app/generateAccessToken" _MESSAGES = { "auth_setup_required": "Dhan automatic auth requires a client ID, six-digit PIN, TOTP secret and valid token-encryption key in server secrets.", "auth_rejected": "Dhan rejected automatic authentication. Verify the server-side credentials and TOTP setup.", "auth_unavailable": "Dhan authentication is temporarily unavailable. Using the existing data fallback.", "auth_cooldown": "Dhan authentication is cooling down. No additional login was attempted.", "auth_storage_error": "Dhan encrypted token storage is unavailable. Check the private persistent disk.", "auth_busy": "Another Dhan authentication request is running. Retry shortly.", } class DhanAuthError(ValueError): def __init__(self, code: str, attempted: bool = False): self.code = code self.attempted = attempted super().__init__(_MESSAGES.get(code, _MESSAGES["auth_unavailable"])) class DhanTokenManager: def __init__(self, client_id: str, pin: str, totp_secret: str, encryption_key: str, session=None, token_path: str | None = None): self.client_id = client_id.strip() self._pin = pin.strip() self._totp_secret = totp_secret.strip().replace(" ", "").upper() self.session = session if session is not None else requests.Session() data_dir = "/data" if os.path.isdir("/data") and os.access("/data", os.W_OK) else os.path.dirname(__file__) self.token_path = token_path or os.path.join(data_dir, ".dhan_auth_token.enc") self._lock = threading.Lock() self._wait = threading.Event() self._fernet = None self._otp = None self._state: dict = {} try: if not self.client_id.isdigit() or not re.fullmatch(r"\d{6}", self._pin): return self._otp = pyotp.TOTP(self._totp_secret) self._otp.byte_secret() self._fernet = Fernet(encryption_key.encode()) except (TypeError, ValueError): self._fernet = None @property def configured(self) -> bool: return self._fernet is not None and self._otp is not None def _read_state(self) -> dict: if not self.configured: return {} try: with open(self.token_path, "rb") as token_file: encrypted = token_file.read(65537) if len(encrypted) > 65536: return {} state = json.loads(self._fernet.decrypt(encrypted)) if isinstance(state, dict) and state.get("client_id") == self.client_id: return state except (OSError, ValueError, TypeError, InvalidToken): pass return {} def _write_state(self, state: dict) -> None: temporary_path = None try: encrypted = self._fernet.encrypt(json.dumps(state, allow_nan=False).encode()) with tempfile.NamedTemporaryFile(mode="wb", dir=os.path.dirname(self.token_path), delete=False) as token_file: temporary_path = token_file.name os.chmod(temporary_path, 0o600) token_file.write(encrypted) token_file.flush() os.fsync(token_file.fileno()) os.replace(temporary_path, self.token_path) except (OSError, ValueError, TypeError): if temporary_path: try: os.unlink(temporary_path) except OSError: pass raise DhanAuthError("auth_storage_error") from None @contextmanager def _file_lock(self, deadline: float): import fcntl descriptor = None acquired = False try: descriptor = os.open(self.token_path + ".lock", os.O_CREAT | os.O_RDWR | getattr(os, "O_NOFOLLOW", 0), 0o600) os.fchmod(descriptor, 0o600) while not acquired: try: fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB) acquired = True except BlockingIOError: remaining = deadline - time.monotonic() if remaining <= 0: raise DhanAuthError("auth_busy") self._wait.wait(min(0.05, remaining)) yield except OSError: raise DhanAuthError("auth_storage_error") from None finally: if descriptor is not None: if acquired: fcntl.flock(descriptor, fcntl.LOCK_UN) os.close(descriptor) def _usable(self, state: dict) -> bool: try: expiry = float(state.get("expires_at", 0)) return (state.get("client_id") == self.client_id and isinstance(state.get("token"), str) and bool(state["token"]) and not state.get("invalidated") and math.isfinite(expiry) and expiry > time.time() + 120) except (ValueError, TypeError): return False @property def needs_refresh(self) -> bool: return not self._usable(dict(self._state)) def get_token(self, timeout: float = 8) -> str: if not self.configured: raise DhanAuthError("auth_setup_required") deadline = time.monotonic() + timeout if not self._lock.acquire(timeout=max(0, timeout)): raise DhanAuthError("auth_busy") try: with self._file_lock(deadline): state = self._read_state() self._state = state if self._usable(state): return state["token"] if float(state.get("next_allowed_at", 0)) > time.time(): raise DhanAuthError("auth_cooldown") remaining = deadline - time.monotonic() if remaining <= 0: raise DhanAuthError("auth_busy") now = time.time() seconds_left = 30 - now % 30 if seconds_left < 3: if remaining <= seconds_left + 1: raise DhanAuthError("auth_busy") self._wait.wait(seconds_left + 0.1) now = time.time() state = {**state, "client_id": self.client_id, "next_allowed_at": now + 120} self._write_state(state) self._state = state attempted = False try: remaining = deadline - time.monotonic() if remaining <= 0: raise DhanAuthError("auth_busy") attempted = True response = self.session.post(_AUTH_URL, params={ "dhanClientId": self.client_id, "pin": self._pin, "totp": self._otp.at(now), }, timeout=min(6, remaining), allow_redirects=False) if response.status_code != 200: raise DhanAuthError("auth_rejected" if response.status_code in (400, 401, 403) else "auth_unavailable", attempted=True) payload = response.json() if not isinstance(payload, dict) or str(payload.get("dhanClientId")) != self.client_id: raise DhanAuthError("auth_rejected", attempted=True) token = payload.get("accessToken") if not isinstance(token, str) or not token or len(token) > 16384: raise DhanAuthError("auth_rejected", attempted=True) expiry = datetime.fromisoformat(payload["expiryTime"].replace("Z", "+00:00")) if expiry.tzinfo is None: expiry = expiry.replace(tzinfo=IST) expires_at = expiry.timestamp() if not now + 120 < expires_at <= now + 86400 + 600: raise DhanAuthError("auth_rejected", attempted=True) state = {"client_id": self.client_id, "token": token, "expires_at": expires_at, "next_allowed_at": now + 120} self._write_state(state) self._state = state return token except DhanAuthError as exc: exc.attempted = exc.attempted or attempted raise except (requests.RequestException, ValueError, TypeError, KeyError, OverflowError): raise DhanAuthError("auth_unavailable", attempted=True) from None finally: self._lock.release() def invalidate(self, rejected_token: str) -> None: if not self.configured: return deadline = time.monotonic() + 2 if not self._lock.acquire(timeout=2): return try: with self._file_lock(deadline): state = self._read_state() if state.get("token") == rejected_token: state["invalidated"] = True self._write_state(state) self._state = state except DhanAuthError: pass finally: self._lock.release() def status(self) -> dict: state = dict(self._state) expires_at = state.get("expires_at") expiry = None try: if expires_at and math.isfinite(float(expires_at)): expiry = datetime.fromtimestamp(float(expires_at), IST).isoformat() except (ValueError, TypeError, OverflowError): pass return {"automatic_auth": True, "auth_ready": self.configured, "requires_daily_login": False, "automatic_token_expiry": expiry} def token_manager_from_env(client_id: str) -> DhanTokenManager | None: if os.getenv("DHAN_AUTO_AUTH", "0") != "1": return None return DhanTokenManager(client_id, os.getenv("DHAN_PIN", ""), os.getenv("DHAN_TOTP_SECRET", ""), os.getenv("DHAN_TOKEN_ENCRYPTION_KEY", ""))