Harden entry safety, unify runtime config, bound document unpacking
Shared-IP safety: entry autoban and entry notifications default off, and a shared IP is treated as review evidence only. ban_user/ban_cluster refuse reason=entry_ip_collision (also with the legacy flag set to 1), so token status and quota are never touched; explicit admin moderation still works. Reproducible startup: new bot/runtime_config.py and scripts/run.py load the repository .env (or --env-file) without shell interpolation, normalize config/DB/upstream aliases, and make the bot, Mini App, gateway, econ cap, account admin, mk_daemon, entry admin and key notifications resolve the same paths. "run.py <target> --check" is an offline preflight that starts nothing and reports placeholders, missing upstream DB and invalid data directories. Resource limits: aggregate Office decompression, a 400 read-entry cap and a per-row XLSX cell budget stop early; truncated or corrupt archives are reported instead of raising. Deploy and docs: only source-backed systemd units remain, and deploy/runtime.env.example documents the environment contract including the 0600 session-secret file rules. Removed the destructive "cp bot/iishko_bot.py bot/grok_bot.py" instruction, the unused generated site/ snapshot and the unsupported iishko-ts staging unit; corrected .env.example, README, ARCHITECTURE, SECURITY, docs/native-gateway.md and iishko-ts/README.md. Tests: entry safety, runtime bootstrap, economy paths, file intake, deploy contract, abilities_guard CLI, and a startup smoke that launches all three components through scripts/run.py with non-loopback network blocked. Every config reader, selfcheck included, accepts a UTF-8 BOM. Verified on this tree: pytest 716 passed + 322 subtests, node --test 73/73, go test and go vet clean, selfcheck --source-only ok, gitleaks worktree and history 0 findings. No production or live-split changes are included.
This commit is contained in:
+140
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Explicit local/service launcher. --check validates config, not live integrations."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
COMPONENTS = {
|
||||
"bot": "bot/grok_bot.py",
|
||||
"miniapp": "bot/webapp/server.py",
|
||||
"gateway": "gateway/grok-web-skin.py",
|
||||
}
|
||||
CONFIG_KEYS = ("GROK_BOT_CFG", "GROK_BOT_CONFIG", "GATE_BOT_CONFIG")
|
||||
PATH_GROUPS = (
|
||||
(("IISHKO_BOT_DB", "GROK_BOT_DB", "GATE_BOT_DB"), "bot_db", "/opt/grok-bot/bot.db"),
|
||||
(("IISHKO_GW_DB", "GATE_NEWAPI_DB"), "newapi_db", "/opt/grok-gateway/new-api/one-api.db"),
|
||||
(("IISHKO_SKIN_DB", "GATE_TG_DB"), None, "/opt/grok-web-skin-tg.db"),
|
||||
)
|
||||
|
||||
|
||||
def _pick(keys, process, file_values, default):
|
||||
# A service/environment alias beats a canonical value in the optional file.
|
||||
for layer in (process, file_values):
|
||||
for key in keys:
|
||||
if layer.get(key):
|
||||
return layer[key]
|
||||
return default
|
||||
|
||||
|
||||
def _path(root, value):
|
||||
path = Path(value).expanduser()
|
||||
return str((root / path).resolve())
|
||||
|
||||
|
||||
def prepare_environment(root=ROOT, env_file=None, process=None):
|
||||
root = Path(root).resolve()
|
||||
process = dict(os.environ if process is None else process)
|
||||
explicit = env_file is not None
|
||||
path = Path(env_file).expanduser() if explicit else root / ".env"
|
||||
if not path.is_absolute():
|
||||
path = root / path
|
||||
file_values = {}
|
||||
if path.exists():
|
||||
from dotenv import dotenv_values
|
||||
# No shell evaluation, parent-file discovery or secret interpolation.
|
||||
file_values = {key: value for key, value in dotenv_values(
|
||||
path, encoding="utf-8-sig", interpolate=False).items() if value is not None}
|
||||
elif explicit:
|
||||
raise ValueError("explicit environment file does not exist")
|
||||
env = {**file_values, **process}
|
||||
config_path = _path(root, _pick(CONFIG_KEYS, process, file_values, "bot/config.json"))
|
||||
for key in CONFIG_KEYS:
|
||||
env[key] = config_path
|
||||
config = {}
|
||||
try:
|
||||
with open(config_path, encoding="utf-8-sig") as source:
|
||||
loaded = json.load(source)
|
||||
if isinstance(loaded, dict):
|
||||
config = loaded
|
||||
except (OSError, ValueError):
|
||||
pass # check_configuration reports the config error without exposing values.
|
||||
for keys, config_key, default in PATH_GROUPS:
|
||||
fallback = config.get(config_key) or default
|
||||
value = _path(root, _pick(keys, process, file_values, fallback))
|
||||
for key in keys:
|
||||
env[key] = value
|
||||
env["IISHKO_APP_ROOT"] = _path(root, _pick(("IISHKO_APP_ROOT",), process, file_values, "bot"))
|
||||
for name in ("TG_SID_SECRET_FILE", "IISHKO_BOT_SOURCE", "IISHKO_PROVIDERS_FILE", "IISHKO_ECON_STATE"):
|
||||
if env.get(name):
|
||||
env[name] = _path(root, env[name])
|
||||
upstream = _pick(("IISHKO_UPSTREAM", "NEWAPI_URL"), process, file_values,
|
||||
config.get("newapi_url"))
|
||||
if upstream:
|
||||
env["IISHKO_UPSTREAM"] = env["NEWAPI_URL"] = upstream
|
||||
module_dirs = [env["IISHKO_APP_ROOT"], str(root / "gateway"), str(root / "bot/webapp")]
|
||||
env["IISHKO_RUNTIME_PATHS"] = os.pathsep.join(module_dirs)
|
||||
# Do not inherit a POSIX-only PYTHONPATH from the distributed .env template.
|
||||
env["PYTHONPATH"] = os.pathsep.join(module_dirs)
|
||||
return env
|
||||
|
||||
|
||||
def check_configuration(env):
|
||||
problems = []
|
||||
try:
|
||||
with open(env["GROK_BOT_CFG"], encoding="utf-8-sig") as source:
|
||||
config = json.load(source)
|
||||
except (OSError, ValueError):
|
||||
return ["bot config is missing, unreadable or invalid JSON (GROK_BOT_CFG)"]
|
||||
if not isinstance(config, dict):
|
||||
return ["bot config must be a JSON object"]
|
||||
for key, name in (("bot_token", "GROK_BOT_TOKEN"), ("newapi_pass", "NEWAPI_PASS")):
|
||||
if env.get(name):
|
||||
config[key] = env[name]
|
||||
for key in ("bot_token", "main_key", "channel_username", "newapi_pass"):
|
||||
value = config.get(key)
|
||||
if not isinstance(value, str) or not value.strip() or "REPLACE_ME" in value or "your_" in value:
|
||||
problems.append("bot config requires a real value for " + key)
|
||||
if not Path(env["IISHKO_APP_ROOT"]).is_dir():
|
||||
problems.append("IISHKO_APP_ROOT must be an existing bot module directory")
|
||||
if not Path(env["IISHKO_GW_DB"]).is_file():
|
||||
problems.append("IISHKO_GW_DB must point to your existing New API SQLite database")
|
||||
for key in ("IISHKO_BOT_DB", "IISHKO_SKIN_DB"):
|
||||
path = Path(env[key])
|
||||
if (path.exists() and not path.is_file()) or not path.parent.is_dir():
|
||||
problems.append(key + " must name a file in an existing data directory")
|
||||
return problems
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("component", choices=COMPONENTS)
|
||||
parser.add_argument("--env-file", help="explicit dotenv file; real environment takes priority")
|
||||
parser.add_argument("--check", action="store_true", help="offline config preflight, not an app smoke test")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
env = prepare_environment(env_file=args.env_file)
|
||||
problems = check_configuration(env)
|
||||
except (OSError, ValueError, ImportError):
|
||||
problems = ["environment setup failed; check the env file and installed requirements"]
|
||||
if problems:
|
||||
for problem in problems:
|
||||
print("ERROR: " + problem, file=sys.stderr)
|
||||
return 2
|
||||
if args.check:
|
||||
print("Configuration preflight passed; no app started or integrations checked.")
|
||||
return 0
|
||||
os.environ.update(env)
|
||||
os.chdir(ROOT)
|
||||
target = ROOT / COMPONENTS[args.component]
|
||||
sys.path[:0] = [str(target.parent), *env["IISHKO_RUNTIME_PATHS"].split(os.pathsep)]
|
||||
sys.argv = [str(target)]
|
||||
runpy.run_path(str(target), run_name="__main__")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -149,13 +149,13 @@ def check_config_templates(problems, notes):
|
||||
notes.append("config template absent (optional): %s" % rel)
|
||||
continue
|
||||
try:
|
||||
json.load(open(path, encoding="utf-8"))
|
||||
json.load(open(path, encoding="utf-8-sig"))
|
||||
except ValueError as exc:
|
||||
problems.append("invalid JSON template %s: %s" % (rel, exc))
|
||||
cfg = os.environ.get("GROK_BOT_CFG") or os.path.join(ROOT, "bot", "config.json")
|
||||
if os.path.isfile(cfg):
|
||||
try:
|
||||
data = json.load(open(cfg, encoding="utf-8"))
|
||||
data = json.load(open(cfg, encoding="utf-8-sig"))
|
||||
placeholders = sorted(k for k, v in data.items()
|
||||
if isinstance(v, str) and ("REPLACE_ME" in v or "your_" in v))
|
||||
if placeholders:
|
||||
|
||||
Reference in New Issue
Block a user