one-command starter for beginners, free socks proxy pool from iishko, iishko gateway shim + channel sql
This commit is contained in:
@@ -0,0 +1,185 @@
|
||||
#!/usr/bin/env python3
|
||||
"""nfgw-shim — OpenAI/Anthropic-compatible shim over Netlify AI Gateway sites.
|
||||
|
||||
Upstream: https://<netlify-site>/.netlify/ai (the gateway proxy edge function).
|
||||
The gateway JWT lives in the edge function env and rotates; this shim pulls a
|
||||
fresh one from /envdump (protected by x-proxy-secret) and caches it briefly.
|
||||
|
||||
Config: /opt/nfgw-shim/sites.json [{"url": "...", "secret": "..."}]
|
||||
Port: NFGW_PORT (default 8833)
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
BASE = '/opt/nfgw-shim'
|
||||
SITES = os.path.join(BASE, 'sites.json')
|
||||
KEY_CACHE = {} # url -> {'key': str, 'ts': float}
|
||||
LOCK = threading.Lock()
|
||||
KEY_TTL = 240 # seconds; JWT lives minutes
|
||||
|
||||
MODELS = [
|
||||
'claude-opus-5-5', 'claude-sonnet-5-5', 'claude-haiku-5-5', 'claude-fable-5-2',
|
||||
'gpt-6.1-sol', 'gpt-6-astra', 'gpt-6-luna', 'gpt-5.5', 'gpt-5.4-mini',
|
||||
'gemini-4-argon', 'gemini-3.8-flash',
|
||||
'x-ai/grok-4.7', 'moonshotai/kimi-k3', 'deepseek/deepseek-v4.1-flash-1017',
|
||||
'z-ai/glm-5.3',
|
||||
]
|
||||
|
||||
|
||||
def load_sites():
|
||||
try:
|
||||
with open(SITES, encoding='utf-8') as f:
|
||||
return json.load(f)
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
def log(msg):
|
||||
line = time.strftime('[%H:%M:%S] ') + str(msg)
|
||||
print(line, flush=True)
|
||||
try:
|
||||
with open(os.path.join(BASE, 'shim.log'), 'a', encoding='utf-8') as f:
|
||||
f.write(line + '\n')
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def fetch_key(site):
|
||||
"""Return a fresh gateway JWT for one site, using the secret-protected envdump."""
|
||||
url = site['url'].rstrip('/')
|
||||
secret = site.get('secret', '')
|
||||
req = urllib.request.Request(url + '/envdump',
|
||||
headers={'x-proxy-secret': secret, 'accept': 'application/json'})
|
||||
with urllib.request.urlopen(req, timeout=25) as r:
|
||||
data = json.loads(r.read().decode())
|
||||
picked = data.get('picked') or {}
|
||||
return picked.get('NETLIFY_AI_GATEWAY_KEY') or picked.get('OPENAI_API_KEY') or ''
|
||||
|
||||
|
||||
def get_key(site, force=False):
|
||||
url = site['url'].rstrip('/')
|
||||
with LOCK:
|
||||
c = KEY_CACHE.get(url)
|
||||
if c and not force and (time.time() - c['ts']) < KEY_TTL:
|
||||
return c['key']
|
||||
key = fetch_key(site)
|
||||
if key:
|
||||
with LOCK:
|
||||
KEY_CACHE[url] = {'key': key, 'ts': time.time()}
|
||||
return key
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
protocol_version = 'HTTP/1.1'
|
||||
|
||||
def log_message(self, fmt, *args):
|
||||
pass
|
||||
|
||||
def _send(self, code, body: bytes, ctype='application/json', extra=None):
|
||||
self.send_response(code)
|
||||
self.send_header('Content-Type', ctype)
|
||||
self.send_header('Content-Length', str(len(body)))
|
||||
for k, v in (extra or {}).items():
|
||||
self.send_header(k, v)
|
||||
self.end_headers()
|
||||
try:
|
||||
self.wfile.write(body)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _json(self, obj, code=200):
|
||||
self._send(code, json.dumps(obj).encode(), 'application/json')
|
||||
|
||||
def do_GET(self):
|
||||
if self.path.startswith('/healthz'):
|
||||
sites = load_sites()
|
||||
return self._json({'ok': True, 'sites': len(sites), 'models': len(MODELS),
|
||||
'cached_keys': len(KEY_CACHE)})
|
||||
if self.path.startswith('/v1/models'):
|
||||
now = int(time.time())
|
||||
return self._json({'object': 'list', 'data': [
|
||||
{'id': m, 'object': 'model', 'created': now, 'owned_by': 'netlify-ai-gateway'}
|
||||
for m in MODELS]})
|
||||
return self._json({'error': {'message': 'not found'}}, 404)
|
||||
|
||||
def do_POST(self):
|
||||
path = self.path
|
||||
length = int(self.headers.get('Content-Length') or 0)
|
||||
body = self.rfile.read(length) if length else b''
|
||||
sites = load_sites()
|
||||
if not sites:
|
||||
return self._json({'error': {'message': 'no sites configured'}}, 500)
|
||||
|
||||
last_err = 'no site tried'
|
||||
for site in sites:
|
||||
for attempt in (0, 1):
|
||||
key = get_key(site, force=(attempt == 1))
|
||||
if not key:
|
||||
last_err = 'no gateway key'
|
||||
continue
|
||||
target = site['url'].rstrip('/') + '/ai' + path # our edge proxy: /.netlify/ai is 403 from DC IPs
|
||||
req = urllib.request.Request(target, data=body if self.command == 'POST' else None,
|
||||
method=self.command)
|
||||
req.add_header('Content-Type', self.headers.get('Content-Type') or 'application/json')
|
||||
req.add_header('Authorization', 'Bearer ' + key)
|
||||
req.add_header('x-api-key', key)
|
||||
av = self.headers.get('anthropic-version')
|
||||
if av:
|
||||
req.add_header('anthropic-version', av)
|
||||
accept = self.headers.get('accept') or ''
|
||||
stream = b'"stream"' in body and b'true' in body
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=180)
|
||||
code = resp.status
|
||||
ctype = resp.headers.get('Content-Type') or 'application/json'
|
||||
if stream or 'event-stream' in ctype:
|
||||
self.send_response(code)
|
||||
self.send_header('Content-Type', ctype or 'text/event-stream')
|
||||
self.send_header('Cache-Control', 'no-cache')
|
||||
self.send_header('Transfer-Encoding', 'chunked')
|
||||
self.end_headers()
|
||||
try:
|
||||
while True:
|
||||
chunk = resp.read(2048)
|
||||
if not chunk:
|
||||
break
|
||||
self.wfile.write(b'%X\r\n' % len(chunk) + chunk + b'\r\n')
|
||||
self.wfile.flush()
|
||||
self.wfile.write(b'0\r\n\r\n')
|
||||
except Exception:
|
||||
pass
|
||||
return
|
||||
data = resp.read()
|
||||
return self._send(code, data, ctype)
|
||||
except urllib.error.HTTPError as e:
|
||||
err_body = e.read()
|
||||
if e.code in (401, 403) and attempt == 0:
|
||||
last_err = f'{e.code} (retry with fresh key)'
|
||||
continue
|
||||
if e.code >= 500:
|
||||
last_err = f'{e.code}'
|
||||
break
|
||||
return self._send(e.code, err_body, e.headers.get('Content-Type') or 'application/json')
|
||||
except Exception as e:
|
||||
last_err = f'{type(e).__name__}: {str(e)[:60]}'
|
||||
continue
|
||||
return self._json({'error': {'message': f'upstream failed: {last_err}'}}, 502)
|
||||
|
||||
|
||||
def main():
|
||||
port = int(os.environ.get('NFGW_PORT', '8833'))
|
||||
sites = load_sites()
|
||||
log(f'start on :{port}, sites={len(sites)}, models={len(MODELS)}')
|
||||
srv = ThreadingHTTPServer(('127.0.0.1', port), Handler)
|
||||
srv.daemon_threads = True
|
||||
srv.serve_forever()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user