1"""Environment-driven settings shared by the API and the bot.
2
3Each concern has its own env prefix: ``DB_``, ``API_``, ``DISCORD_``, ``WEB_``.
4"""
5
6import json
7from typing import Annotated, Any
8
9from pydantic import SecretStr, field_validator, model_validator
10from pydantic_settings import BaseSettings, NoDecode, SettingsConfigDict
11
12_BASE_CONFIG = {"env_file": ".env", "extra": "ignore", "case_sensitive": False}
13MIN_SESSION_SECRET_LENGTH = 32
14
15
[docs]
16class DatabaseSettings(BaseSettings):
17 """Database connection settings (``DB_*``)."""
18
19 model_config = SettingsConfigDict(env_prefix="DB_", **_BASE_CONFIG)
20
21 URL: str = "postgresql+asyncpg://sidequest:sidequest@localhost:55432/sidequest"
22 ECHO: bool = False
23 POOL_DISABLE: bool = False
24
25
[docs]
26class APISettings(BaseSettings):
27 """API settings (``API_*``).
28
29 ``KEY`` is the shared secret the bot sends as ``X-API-Key``; both services must agree on it.
30 ``URL`` is where the bot reaches the API.
31 """
32
33 model_config = SettingsConfigDict(env_prefix="API_", **_BASE_CONFIG)
34
35 KEY: SecretStr
36 URL: str = "http://localhost:8000"
37 HOST: str = "127.0.0.1"
38 PORT: int = 8000
39 DEBUG: bool = False
40
41
[docs]
42class WowSimsSettings(BaseSettings):
43 """wowsims/forever CLI location (``WOWSIMS_*``).
44
45 ``DIR`` holds ``bin/wowsimcli``, ``sim/siml/names.json``, ``assets/database/db.json`` and ``ui/specs/**``, the
46 same layout the Dockerfile's Go build stage produces under ``/opt/wowsims`` and ``~/.cache/wowsims-forever``
47 has locally after the wow-forever-sim skill's ``setup`` command. ``RUNNER`` starts the background loop that runs
48 queued sims in this process (it also needs the binary to exist); tests that only queue jobs turn it off.
49 """
50
51 model_config = SettingsConfigDict(env_prefix="WOWSIMS_", **_BASE_CONFIG)
52
53 DIR: str = "/opt/wowsims"
54 RUNNER: bool = True
55
56
[docs]
57class DiscordSettings(BaseSettings):
58 """Discord bot settings (``DISCORD_*``).
59
60 ``GUILD_ID`` is optional; when set, slash commands sync to that guild instantly instead of globally.
61 """
62
63 model_config = SettingsConfigDict(env_prefix="DISCORD_", **_BASE_CONFIG)
64
65 TOKEN: SecretStr
66 GUILD_ID: int | None = None
67
68 @field_validator("TOKEN")
69 @classmethod
70 def _token_must_not_be_empty(cls, value: SecretStr) -> SecretStr:
71 """Reject an empty token, such as a blank ``DISCORD_TOKEN=`` line in ``.env``, as if it were unset."""
72 if not value.get_secret_value():
73 msg = "DISCORD_TOKEN must not be empty"
74 raise ValueError(msg)
75 return value
76
77
[docs]
78class WebSettings(BaseSettings):
79 """Member hub / website settings (``WEB_*``).
80
81 Discord OAuth2 login (scopes ``identify guilds.members.read``) for guild members, guild events, and addons.
82 ``DISCORD_CLIENT_ID``/``DISCORD_CLIENT_SECRET`` are the OAuth *application* credentials (separate from the
83 bot's ``DISCORD_TOKEN``); when either is unset the app still boots, but ``/auth/discord/login`` returns 503.
84 ``BATTLENET_CLIENT_ID``/``BATTLENET_CLIENT_SECRET`` (a develop.battle.net API client) let signed-in members link
85 their Battle.net account; when unset, linking redirects back to the account page with an explanation.
86 ``BATTLENET_STATIC_VERSION`` pins Battle.net's static game data (playable classes, items, talents and the
87 rest of what only changes with a patch) to one build, such as ``"1.60.1_70399"``, instead of Battle.net's
88 current static namespace; unset (the default) keeps today's behavior. Opt-in because whether Blizzard keeps
89 an old static namespace reachable after a patch is unknown, so forcing a pin could 404 the whole site once
90 one ships.
91 """
92
93 model_config = SettingsConfigDict(env_prefix="WEB_", **_BASE_CONFIG)
94
95 BASE_URL: str = "http://localhost:8000"
96 SESSION_SECRET: SecretStr | None = None
97 DISCORD_CLIENT_ID: str | None = None
98 DISCORD_CLIENT_SECRET: SecretStr | None = None
99 BATTLENET_CLIENT_ID: str | None = None
100 BATTLENET_CLIENT_SECRET: SecretStr | None = None
101 BATTLENET_STATIC_VERSION: str | None = None
102 GUILD_ID: int = 1564671275316543508
103 # Defaults are the SideQuest server's Quest Master (GM) and Quest Guide roles, like GUILD_ID above; the env vars
104 # override them. NoDecode: parsed by _parse_role_ids, so both `123,456` and `[123,456]` work in .env.
105 OFFICER_ROLE_IDS: Annotated[list[int], NoDecode] = [1564678042381586532, 1564678035117178960]
106 GM_ROLE_IDS: Annotated[list[int], NoDecode] = [1564678042381586532]
107 COOKIE_SECURE: bool = False
108 MARKET_FEED_KEY: SecretStr | None = None
109 """Shared secret the market report feed sends as ``X-Market-Key``; unset, ``POST /api/market/feed`` is 503."""
110 VAULT_KEY: SecretStr | None = None
111 """Shared secret for the owner-only vault, sent as ``X-Vault-Key``; unset, every ``/api/vault`` route is 503."""
112
113 @property
114 def oauth_configured(self) -> bool:
115 """Whether both Discord OAuth app credentials are set."""
116 return self.DISCORD_CLIENT_ID is not None and self.DISCORD_CLIENT_SECRET is not None
117
118 @property
119 def battlenet_configured(self) -> bool:
120 """Whether both Battle.net OAuth client credentials are set."""
121 return self.BATTLENET_CLIENT_ID is not None and self.BATTLENET_CLIENT_SECRET is not None
122
123 @field_validator("OFFICER_ROLE_IDS", "GM_ROLE_IDS", mode="before")
124 @classmethod
125 def _parse_role_ids(cls, value: Any) -> Any:
126 """Accept a JSON array (``[123,456]``) or a comma-separated list (``123,456``) from the environment."""
127 if not isinstance(value, str):
128 return value
129 text = value.strip()
130 if text.startswith("["):
131 return json.loads(text)
132 return [part.strip() for part in text.split(",") if part.strip()]
133
134 @model_validator(mode="after")
135 def _validate_session_secret_length(self) -> WebSettings:
136 if self.SESSION_SECRET is not None and len(self.SESSION_SECRET.get_secret_value()) < MIN_SESSION_SECRET_LENGTH:
137 msg = f"WEB_SESSION_SECRET must be at least {MIN_SESSION_SECRET_LENGTH} characters"
138 raise ValueError(msg)
139 return self