My NixOS configurations + dotfiles

server/slop: package brave-shim and run via user systemd service

kris.darkworld.download a271d6c3 872df782

verified
+206 -9
+201
hosts/server/slop/brave-shim.nix
··· 1 + { pkgs }: 2 + 3 + let 4 + pythonEnv = pkgs.python3.withPackages (ps: with ps; [ 5 + fastapi 6 + uvicorn 7 + ddgs 8 + pyyaml 9 + ]); 10 + in 11 + pkgs.stdenvNoCC.mkDerivation { 12 + pname = "brave-shim"; 13 + version = "0.1.0"; 14 + dontUnpack = true; 15 + 16 + installPhase = '' 17 + mkdir -p $out/bin $out/share/brave-shim 18 + 19 + cat > $out/share/brave-shim/brave_shim.conf <<'CONF' 20 + server: 21 + host: "127.0.0.1" 22 + port: 8000 23 + 24 + ssl: 25 + use_custom_ca: false 26 + ca_bundle_path: "/etc/ssl/certs/ca-certificates.crt" 27 + verify_ssl: true 28 + 29 + logging: 30 + file_path: "/home/ocbwoy3/.local/state/brave-shim/brave_shim.log" 31 + level: "INFO" 32 + 33 + bot_protection: 34 + cache_expiration: 3600 35 + min_delay: 1.0 36 + max_delay: 2.5 37 + 38 + search: 39 + default_count: 10 40 + local_count: 5 41 + CONF 42 + 43 + cat > $out/share/brave-shim/brave_shim.py <<'PY' 44 + import time 45 + import random 46 + import yaml 47 + import uvicorn 48 + import logging 49 + import os 50 + import ssl 51 + from fastapi import FastAPI, Query 52 + from ddgs import DDGS 53 + from pathlib import Path 54 + 55 + config_path = Path(os.environ.get("BRAVE_SHIM_CONF", "brave_shim.conf")) 56 + if not config_path.exists(): 57 + raise FileNotFoundError(f"Config not found: {config_path}") 58 + 59 + with open(config_path, "r") as f: 60 + config = yaml.safe_load(f) 61 + 62 + os.makedirs(os.path.dirname(config["logging"]["file_path"]), exist_ok=True) 63 + logging.basicConfig( 64 + level=config['logging']['level'], 65 + format="%(asctime)s [%(levelname)s] %(message)s", 66 + handlers=[logging.FileHandler(config['logging']['file_path'])] 67 + ) 68 + logger = logging.getLogger("brave_shim") 69 + 70 + ssl_cfg = config.get('ssl', {}) 71 + verify_ssl = ssl_cfg.get('verify_ssl', True) 72 + custom_ca_status = "System Default" 73 + 74 + if ssl_cfg.get('use_custom_ca'): 75 + ca_path = ssl_cfg['ca_bundle_path'] 76 + if os.path.exists(ca_path): 77 + os.environ["SSL_CERT_FILE"] = ca_path 78 + os.environ["REQUESTS_CA_BUNDLE"] = ca_path 79 + os.environ["CURL_CA_BUNDLE"] = ca_path 80 + 81 + if not verify_ssl: 82 + ssl._create_default_https_context = ssl._create_unverified_context 83 + custom_ca_status = f"Active (Verify=OFF, Path={ca_path})" 84 + logger.warning("SSL verification disabled") 85 + else: 86 + try: 87 + context = ssl.create_default_context(cafile=ca_path) 88 + ssl._create_default_https_context = lambda: context 89 + custom_ca_status = f"Active (Path={ca_path})" 90 + except Exception as e: 91 + logger.error(f"SSL bundle load error: {e}") 92 + else: 93 + logger.error(f"SSL CA bundle not found: {ca_path}") 94 + custom_ca_status = "Error: File not found" 95 + 96 + app = FastAPI(title="Brave Search API Shim", docs_url=None, redoc_url=None) 97 + search_cache = {} 98 + 99 + def get_from_cache(q): 100 + expiration = config['bot_protection']['cache_expiration'] 101 + if q in search_cache: 102 + timestamp, data = search_cache[q] 103 + if time.time() - timestamp < expiration: 104 + return data 105 + return None 106 + 107 + @app.get("/status") 108 + async def health_check(): 109 + return { 110 + "status": "online", 111 + "cache_entries": len(search_cache), 112 + "ssl_verify": verify_ssl, 113 + "ca_bundle": custom_ca_status 114 + } 115 + 116 + @app.get("/res/v1/web/search") 117 + async def search_proxy(q: str = Query(...), count: int = None): 118 + res_count = count or config['search']['default_count'] 119 + cached_res = get_from_cache(q) 120 + if cached_res: 121 + logger.info(f"CACHE HIT: {q}") 122 + return cached_res 123 + 124 + time.sleep(random.uniform(config['bot_protection']['min_delay'], config['bot_protection']['max_delay'])) 125 + logger.info(f"FETCH WEB: {q}") 126 + try: 127 + with DDGS(verify=verify_ssl) as ddgs: 128 + results = [] 129 + for r in ddgs.text(q, max_results=res_count): 130 + results.append({ 131 + "title": r.get("title"), 132 + "url": r.get("href"), 133 + "description": r.get("body"), 134 + "meta_url": {"path": r.get("href")} 135 + }) 136 + 137 + response_data = {"web": {"results": results}} 138 + search_cache[q] = (time.time(), response_data) 139 + return response_data 140 + except Exception as e: 141 + logger.error(f"WEB search error for '{q}': {e}") 142 + return {"web": {"results": []}, "error": str(e)} 143 + 144 + @app.get("/res/v1/local/pois") 145 + async def local_proxy(q: str = Query(...), count: int = None): 146 + res_count = count or config['search']['local_count'] 147 + logger.info(f"FETCH LOCAL: {q}") 148 + try: 149 + with DDGS(verify=verify_ssl) as ddgs: 150 + res = [ 151 + { 152 + "id": str(i), 153 + "name": r["title"], 154 + "address": r["body"][:100], 155 + "phone": "", 156 + "coordinates": {"latitude": 0.0, "longitude": 0.0} 157 + } 158 + for i, r in enumerate(ddgs.text(f"place {q}", max_results=res_count)) 159 + ] 160 + return {"results": res} 161 + except Exception as e: 162 + logger.error(f"LOCAL search error for '{q}': {e}") 163 + return {"results": []} 164 + 165 + @app.get("/res/v1/local/descriptions") 166 + async def local_descriptions(id: str = Query(...)): 167 + return {"descriptions": {id: "Data from DDGS proxy."}} 168 + 169 + @app.get("/res/v1/summarizer/summary") 170 + async def summarizer_proxy(key: str = Query(...)): 171 + return {"summary": "Summary ready.", "status": "complete"} 172 + 173 + if __name__ == "__main__": 174 + logger.info(f"Starting brave-shim on {config['server']['host']}:{config['server']['port']}") 175 + uvicorn.run( 176 + app, 177 + host=config['server']['host'], 178 + port=config['server']['port'], 179 + access_log=False, 180 + log_level="critical" 181 + ) 182 + PY 183 + 184 + cat > $out/bin/brave-shim <<EOF 185 + #!${pkgs.bash}/bin/bash 186 + set -euo pipefail 187 + export BRAVE_SHIM_CONF=\"\ 188 + s h\ 189 + \" 190 + EOF 191 + 192 + # simpler wrapper (avoid quoting bugs) 193 + cat > $out/bin/brave-shim <<EOF 194 + #!${pkgs.bash}/bin/bash 195 + set -euo pipefail 196 + export BRAVE_SHIM_CONF="''${BRAVE_SHIM_CONF:-$out/share/brave-shim/brave_shim.conf}" 197 + exec ${pythonEnv}/bin/python $out/share/brave-shim/brave_shim.py 198 + EOF 199 + chmod +x $out/bin/brave-shim 200 + ''; 201 + }
+4 -9
hosts/server/slop/brave.nix
··· 1 1 { pkgs, ... }: 2 2 3 + let 4 + braveShim = pkgs.callPackage ./brave-shim.nix { }; 5 + in 3 6 { 4 7 # Local Brave API shim as a user service 5 8 systemd.user.services.brave-shim = { ··· 10 13 11 14 serviceConfig = { 12 15 Type = "simple"; 13 - WorkingDirectory = "/home/ocbwoy3/Projects/brave_shim"; 14 - ExecStart = '' 15 - ${pkgs.uv}/bin/uv run \ 16 - --with fastapi \ 17 - --with uvicorn \ 18 - --with ddgs \ 19 - --with pyyaml \ 20 - python brave_shim.py 21 - ''; 16 + ExecStart = "${braveShim}/bin/brave-shim"; 22 17 Restart = "always"; 23 18 RestartSec = "3"; 24 19 };
+1
hosts/server/slop/openclaw.nix
··· 25 25 packages = [ 26 26 openclawPatched 27 27 (pkgs.callPackage ./gogcli.nix { }) 28 + (pkgs.callPackage ./brave-shim.nix { }) 28 29 pkgs.uv 29 30 pkgs.python3 30 31 ];