Repository navigation
Expand file tree
/
Copy pathapi_server.py
More file actions
1900 lines (1702 loc) · 86.5 KB
/
Copy pathapi_server.py
File metadata and controls
1900 lines (1702 loc) · 86.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
answerr REST API (v1.3.0)
ITouch Bilişim Sistemleri Ltd. Şti. — https://answerr.me
Endpoints
GET / service info
GET /v1/health health
GET /v1/presets, /v1/domains demo catalog
POST /v1/decide typed decision; inline `policy` or `gate_id`; full trace
GET /v1/gates built-in gates (+ your own with an API key)
POST /v1/gates register a gate (API key required)
DELETE /v1/gates/{gate_id} delete your gate (API key required)
POST /v1/gates/{gate_id}/decide decide with a gate (API key required for custom gates)
POST /v1/policies/compile natural language -> draft policy, tests and checks (never registers)
POST /v1/systemone JevBench wire format (research)
POST /v1/chat/completions OpenAI-compatible adapter (research)
… /v1/auth, /v1/account, /v1/reviews, /v1/backtest, /v1/plans, /v1/admin commercial layer (commerce/router.py)
GET /v1/docs, /v1/redoc, /v1/openapi.json interactive reference (under /v1 because only /v1 is proxied)
Verdicts for gated / strict / agent-tool requests come from policy_kernel.py, which is
mirrored by js/policy-kernel.js and checked for parity in tests/.
Configuration (environment, e.g. /etc/answerr/answerr.env):
ANSWERR_API_KEYS "tenant1:key1,tenant2:key2"
ANSWERR_GATES_PATH custom gate store (default /var/lib/answerr/gates.json)
ANSWERR_RATELIMIT_DB shared rate-limit store for all workers (default /var/lib/answerr/ratelimit.sqlite)
ANSWERR_TRUSTED_PROXIES hops skipped in X-Forwarded-For (default 127.0.0.1,::1,10.0.2.2 = VirtualBox NAT)
RECAPTCHA_SECRET reCAPTCHA v3 secret for the answerr.me site key
RECAPTCHA_MIN_SCORE default 0.5
RECAPTCHA_HOSTNAMES default answerr.me,www.answerr.me
ANSWERR_WERR_PATH path of the werr research package (default /home/pcworm/werr)
ANSWERR_COMMERCE_DB accounts, keys, usage, decision log, reviews (default /var/lib/answerr/commerce.sqlite)
ANSWERR_ADMIN_KEY ITouch operations key for /v1/admin/* (>= 24 chars; unset = admin API off)
ANSWERR_CONSOLE_URL console address used in sign-in e-mails (default https://answerr.me/pro/console/)
ANSWERR_PAYMENT_PROVIDER manual (default) | iyzico (see docs/commerce/IYZICO_ENTEGRASYONU.md)
"""
import hashlib
import hmac
import json
import math
import os
import re
import sys
import tempfile
import threading
import time
import urllib.parse
import urllib.request
from collections import defaultdict, deque
from contextlib import asynccontextmanager
from typing import Any, Dict, List, Optional, Tuple, Union
from fastapi import FastAPI, HTTPException, Request, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
sys.path.insert(1, os.environ.get("ANSWERR_WERR_PATH", "/home/pcworm/werr"))
import werr # noqa: E402 (research engine: fractal telemetry, choice/score, legacy presets)
import werr as wevv # noqa: E402,F401 backward-compatibility alias
import access_mailer # noqa: E402
import policy_checks # noqa: E402
import policy_compiler # noqa: E402
import policy_kernel as PK # noqa: E402
from commerce import mail as CMAIL # noqa: E402
from commerce import router as CROUTER # noqa: E402
from commerce import store as CS # noqa: E402
from commerce import webhooks as CHOOKS # noqa: E402
API_VERSION = "1.3.0"
START_TIME = time.time()
# -----------------------------------------------------------------------------
# Configuration
# -----------------------------------------------------------------------------
def _parse_keys(raw: str) -> Dict[str, str]:
out = {}
for part in (raw or "").split(","):
part = part.strip()
if not part or ":" not in part:
continue
tenant, key = part.split(":", 1)
if tenant.strip() and len(key.strip()) >= 24:
out[key.strip()] = tenant.strip()
return out
API_KEYS = _parse_keys(os.environ.get("ANSWERR_API_KEYS", ""))
GATES_PATH = os.environ.get("ANSWERR_GATES_PATH", "/var/lib/answerr/gates.json")
TRUSTED_PROXIES = {p.strip() for p in os.environ.get("ANSWERR_TRUSTED_PROXIES", "127.0.0.1,::1,10.0.2.2").split(",") if p.strip()}
RECAPTCHA_SECRET = os.environ.get("RECAPTCHA_SECRET", "").strip()
RECAPTCHA_MIN_SCORE = float(os.environ.get("RECAPTCHA_MIN_SCORE", "0.5"))
RECAPTCHA_HOSTNAMES = {h.strip() for h in os.environ.get("RECAPTCHA_HOSTNAMES", "answerr.me,www.answerr.me").split(",") if h.strip()}
RECAPTCHA_ACTIONS = {"decide", "compile", "sandbox", "access"}
GATE_ID_RE = re.compile(r"^[a-z0-9][a-z0-9_\-]{2,63}$")
MAX_GATES_TOTAL = 1000
MAX_GATES_PER_TENANT = 200
MAX_RULES = 100
MAX_REQUEST_BODY_BYTES = 65536
def _bearer(request: Request) -> str:
key = request.headers.get("x-api-key") or ""
auth = request.headers.get("authorization") or ""
if not key and auth.lower().startswith("bearer "):
key = auth[7:].strip()
return key
def authenticate_principal(request: Request) -> Tuple[Optional[str], Optional[Dict[str, Any]]]:
"""(tenant, principal). Internal keys from ANSWERR_API_KEYS give a tenant without a principal
(no metering). Customer API keys (ans_live_) and console sessions (ans_sess_) give tenant
'acct:<id>' and a principal with account, role and channel."""
key = _bearer(request)
if not key:
return None, None
if key.startswith("ans_live_") or key.startswith("ans_sess_"):
try:
p = CS.resolve_api_key(key) if key.startswith("ans_live_") else CS.resolve_session(key)
except Exception as e: # commerce store unavailable: treat as anonymous, never 500
print("[answerr] commerce auth unavailable:", e, file=sys.stderr)
p = None
return ("acct:" + p["account_id"], p) if p else (None, None)
for k, tenant in API_KEYS.items():
if hmac.compare_digest(k.encode(), key.encode()):
return tenant, None
return None, None
def authenticate(request: Request) -> Optional[str]:
"""Returns the tenant name for a valid key or session, else None."""
return authenticate_principal(request)[0]
def _strip_port(entry: str) -> str:
e = entry.strip().strip('"')
if e.startswith("["): # [ipv6]:port
return e[1:e.index("]")] if "]" in e else e
if e.count(":") == 1: # ipv4:port (IIS ARR appends the client port)
return e.split(":", 1)[0]
return e
def client_ip(request: Request) -> str:
"""Real client address behind IIS (ARR) -> VirtualBox NAT -> Apache -> uvicorn.
IIS appends "client:port" to X-Forwarded-For and Apache appends the NAT gateway
(10.0.2.2), so a request reaches us as XFF="<anything the client sent>, client:port, 10.0.2.2"
from peer 127.0.0.1. Walking the chain from the right and skipping trusted hops
yields the address IIS saw; entries the client wrote itself are never reached."""
peer = request.client.host if request.client else "0.0.0.0"
if peer not in TRUSTED_PROXIES:
return peer
chain = [_strip_port(p) for p in (request.headers.get("x-forwarded-for") or "").split(",") if p.strip()]
for hop in reversed(chain):
if hop and hop not in TRUSTED_PROXIES:
return hop
real = (request.headers.get("x-real-ip") or "").strip()
return real or peer
def via_iis(request: Request) -> bool:
return bool(request.headers.get("x-arr-log-id"))
# -----------------------------------------------------------------------------
# Rate limiting (per client IP, or per tenant for API-key callers)
# -----------------------------------------------------------------------------
class SlidingWindowLimiter:
"""Sliding-window limiter shared by all uvicorn workers through one SQLite file
(ANSWERR_RATELIMIT_DB). Falls back to per-process memory if the file is unusable."""
TIERS = {
"anonymous": (60, 10), # per window, per second
"verified": (120, 20), # reCAPTCHA-verified browser
"api_key": (600, 50),
"direct_shared": (300, 30), # all non-IIS (direct :4431) anonymous traffic together
"access_form": (5, 5), # early-access form: 5 per hour per IP (window set below)
}
def __init__(self, window_seconds: int = 60, name: str = "rl"):
self.window = window_seconds
self.name = name
self.lock = threading.Lock()
self.hits: Dict[str, deque] = defaultdict(deque)
self.last_cleanup = time.time()
self.db_path = os.environ.get("ANSWERR_RATELIMIT_DB", "/var/lib/answerr/ratelimit.sqlite")
self._local = threading.local()
self.shared = self._init_db()
def _conn(self):
import sqlite3
c = getattr(self._local, "conn", None)
if c is None:
c = sqlite3.connect(self.db_path, timeout=2.0, isolation_level=None)
c.execute("PRAGMA journal_mode=WAL")
c.execute("PRAGMA synchronous=OFF")
self._local.conn = c
return c
def _init_db(self) -> bool:
try:
os.makedirs(os.path.dirname(self.db_path) or ".", exist_ok=True)
c = self._conn()
c.execute("CREATE TABLE IF NOT EXISTS hits (k TEXT NOT NULL, ts REAL NOT NULL)")
c.execute("CREATE INDEX IF NOT EXISTS hits_k_ts ON hits (k, ts)")
return True
except Exception as e:
print("[answerr] shared rate limiter unavailable, using per-process memory:", e, file=sys.stderr)
return False
def check(self, ident: str, tier: str) -> Tuple[bool, int, int, int]:
per_win, per_sec = self.TIERS[tier]
key = "{}:{}:{}".format(self.name, tier, ident)
now = time.time()
if self.shared:
try:
return self._check_db(key, now, per_win, per_sec)
except Exception:
pass # fall through to memory
return self._check_mem(key, now, per_win, per_sec)
def _check_db(self, key, now, per_win, per_sec):
c = self._conn()
c.execute("BEGIN IMMEDIATE")
try:
if now - self.last_cleanup > 300:
c.execute("DELETE FROM hits WHERE ts < ?", (now - 3600,))
self.last_cleanup = now
c.execute("DELETE FROM hits WHERE k = ? AND ts < ?", (key, now - self.window))
n_win, oldest, n_sec = c.execute(
"SELECT COUNT(*), MIN(ts), SUM(CASE WHEN ts >= ? THEN 1 ELSE 0 END) FROM hits WHERE k = ?",
(now - 1.0, key)).fetchone()
n_sec = n_sec or 0
if n_sec >= per_sec:
c.execute("COMMIT")
return False, per_win, 0, 1
if n_win >= per_win:
c.execute("COMMIT")
return False, per_win, 0, max(1, int(self.window - (now - (oldest or now))))
c.execute("INSERT INTO hits (k, ts) VALUES (?, ?)", (key, now))
c.execute("COMMIT")
return True, per_win, per_win - n_win - 1, 0
except Exception:
c.execute("ROLLBACK")
raise
def _check_mem(self, key, now, per_win, per_sec):
with self.lock:
if now - self.last_cleanup > 300:
cutoff = now - self.window
for k in [k for k, q in self.hits.items() if not q or q[-1] < cutoff]:
del self.hits[k]
self.last_cleanup = now
q = self.hits[key]
while q and q[0] < now - self.window:
q.popleft()
if sum(1 for t in q if t >= now - 1.0) >= per_sec:
return False, per_win, 0, 1
if len(q) >= per_win:
return False, per_win, 0, max(1, int(self.window - (now - q[0])))
q.append(now)
return True, per_win, per_win - len(q), 0
LIMITER = SlidingWindowLimiter()
# -----------------------------------------------------------------------------
# reCAPTCHA v3 — verified on the server, result cached per token
# -----------------------------------------------------------------------------
_RECAPTCHA_CACHE: Dict[str, Tuple[float, str]] = {}
_RECAPTCHA_LOCK = threading.Lock()
def verify_recaptcha(token: Optional[str], ip: str) -> str:
"""Returns 'verified', 'failed', 'absent' or 'not_configured'."""
if not token:
return "absent"
if not RECAPTCHA_SECRET:
return "not_configured"
digest = hashlib.sha256(token.encode()).hexdigest()
now = time.time()
with _RECAPTCHA_LOCK:
hit = _RECAPTCHA_CACHE.get(digest)
if hit and now - hit[0] < 120:
return hit[1]
status = "failed"
try:
data = urllib.parse.urlencode({"secret": RECAPTCHA_SECRET, "response": token, "remoteip": ip}).encode()
req = urllib.request.Request("https://www.google.com/recaptcha/api/siteverify", data=data, method="POST")
with urllib.request.urlopen(req, timeout=3) as resp:
body = json.loads(resp.read().decode("utf-8"))
if (body.get("success") and float(body.get("score", 0)) >= RECAPTCHA_MIN_SCORE
and body.get("hostname") in RECAPTCHA_HOSTNAMES
and body.get("action") in RECAPTCHA_ACTIONS):
status = "verified"
except Exception:
status = "failed"
with _RECAPTCHA_LOCK:
if len(_RECAPTCHA_CACHE) > 5000:
_RECAPTCHA_CACHE.clear()
_RECAPTCHA_CACHE[digest] = (now, status)
return status
# -----------------------------------------------------------------------------
# Gate registry: built-in gates (read-only) + tenant gates persisted to disk
# -----------------------------------------------------------------------------
def _load_builtin() -> Dict[str, Dict[str, Any]]:
with open(os.path.join(HERE, "policies", "builtin_gates.json"), encoding="utf-8") as f:
gates = json.load(f)
for g in gates.values():
g["policy_seal"] = PK.policy_seal(g)
return gates
class GateStore:
"""Tenant gates in one JSON file. Safe with several uvicorn workers: writes take an
exclusive flock and replace the file atomically; readers reload when the mtime changes."""
def __init__(self, path: str):
self.path = path
self.lock = threading.Lock()
self.gates: Dict[str, Dict[str, Any]] = {}
self._mtime = None
self.available = True
self._reload(force=True)
def _reload(self, force: bool = False):
if not self.available:
return
try:
st = os.stat(self.path)
# inode changes on every atomic replace; mtime alone can repeat within one clock tick
m = (st.st_ino, st.st_mtime_ns, st.st_size)
except FileNotFoundError:
self.gates, self._mtime = {}, None
return
if not force and m == self._mtime:
return
try:
with open(self.path, encoding="utf-8") as f:
data = json.load(f)
self.gates = data if isinstance(data, dict) else {}
self._mtime = m
except Exception as e: # corrupt store: keep serving built-ins, never overwrite it
print("[answerr] gate store unreadable, tenant gates disabled:", e, file=sys.stderr)
self.available = False
def _locked(self):
import fcntl
class _L:
def __enter__(s):
d = os.path.dirname(self.path) or "."
os.makedirs(d, exist_ok=True)
s.f = open(self.path + ".lock", "a")
fcntl.flock(s.f, fcntl.LOCK_EX)
return s
def __exit__(s, *a):
fcntl.flock(s.f, fcntl.LOCK_UN)
s.f.close()
return _L()
def _save(self):
d = os.path.dirname(self.path) or "."
fd, tmp = tempfile.mkstemp(dir=d, prefix=".gates.", suffix=".json")
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(self.gates, f, ensure_ascii=False, indent=1, sort_keys=True)
os.chmod(tmp, 0o600)
os.replace(tmp, self.path)
st = os.stat(self.path)
self._mtime = (st.st_ino, st.st_mtime_ns, st.st_size)
def get(self, gate_id: str) -> Optional[Dict[str, Any]]:
self._reload()
return self.gates.get(gate_id)
def owned_by(self, tenant: str) -> List[Dict[str, Any]]:
self._reload()
return [g for g in self.gates.values() if g.get("tenant") == tenant]
def count(self) -> int:
self._reload()
return len(self.gates)
def put(self, gate: Dict[str, Any], tenant: str):
if not self.available:
raise HTTPException(503, "Gate store is unavailable.")
with self.lock, self._locked():
self._reload(force=True)
existing = self.gates.get(gate["gate_id"])
if existing and existing.get("tenant") != tenant:
raise HTTPException(403, "Gate id belongs to another tenant.")
if not existing:
if len(self.gates) >= MAX_GATES_TOTAL:
raise HTTPException(507, "Gate store is full.")
if sum(1 for g in self.gates.values() if g.get("tenant") == tenant) >= MAX_GATES_PER_TENANT:
raise HTTPException(429, "Gate limit for this tenant reached.")
self.gates[gate["gate_id"]] = gate
self._save()
def drop_tenant(self, tenant: str) -> int:
if not self.available:
return 0
with self.lock, self._locked():
self._reload(force=True)
ids = [k for k, g in self.gates.items() if g.get("tenant") == tenant]
for k in ids:
del self.gates[k]
if ids:
self._save()
return len(ids)
def delete(self, gate_id: str, tenant: str) -> bool:
if not self.available:
raise HTTPException(503, "Gate store is unavailable.")
with self.lock, self._locked():
self._reload(force=True)
g = self.gates.get(gate_id)
if not g:
return False
if g.get("tenant") != tenant:
raise HTTPException(403, "Gate id belongs to another tenant.")
del self.gates[gate_id]
self._save()
return True
BUILTIN_GATES = _load_builtin()
GATE_STORE = GateStore(GATES_PATH)
COMMERCIAL_GATES = BUILTIN_GATES # backward-compatible name used by older clients/tests
def resolve_gate(gate_id: Optional[str], tenant: Optional[str]) -> Optional[Dict[str, Any]]:
if not gate_id:
return None
if gate_id in BUILTIN_GATES:
return BUILTIN_GATES[gate_id]
g = GATE_STORE.get(gate_id)
if not g:
raise HTTPException(404, "Gate '{}' not found.".format(gate_id))
if g.get("tenant") != tenant:
raise HTTPException(401 if tenant is None else 403, "This gate needs its owner's API key.")
return g
# -----------------------------------------------------------------------------
# Research engine instances (werr)
# -----------------------------------------------------------------------------
DEFAULT_ROUTER = werr.create_smart_router()
SYSTEMONE_ROUTER = werr.WerrEngine(
enable_domain=True, enable_lexical=True, enable_resonance=True,
mode="hybrid", domain_mode="multi", tripod=True,
)
DOMAIN_GATES = werr.DOMAIN_GATES
# Predefined domain presets matching answerr.me web client
PRESETS = {
"api_security": {
"title": "API Gateway & Security Guard",
"description": "Zero-trust sub-millisecond edge firewall packet & credential evaluation",
"default_state": {"user_role": "guest", "failed_attempts": 2, "req_frequency": 12.0},
"default_questions": {
"allow_request": {"type": "noul", "text": "Should this incoming request be permitted through?"},
"route_destination": {
"type": "choice",
"text": "Target gateway pipeline",
"criteria": {
"direct_api": "Direct API route (Fast Path)",
"rate_limiter": "Rate limiter queue buffer",
"sandbox_audit": "Sandbox quarantine / Auth challenge",
"drop_packet": "Drop packet & block IP"
}
},
"threat_score": {
"type": "score",
"text": "Threat assessment score",
"criteria": ["Clean / Safe", "Minor Anomaly", "High Risk", "Critical Threat"]
}
}
},
"ddos_mitigation": {
"title": "L7 Edge DDoS & Bot Mitigation",
"description": "Adaptive volumetric traffic filtering and rate governor",
"default_state": {"syn_rate": 840, "ua_entropy": 0.12, "geo_burst": True, "failed_ratio": 0.88},
"default_questions": {
"pass_filter": {"type": "noul", "text": "Pass packet without challenge?"},
"defense_action": {
"type": "choice",
"text": "Mitigation strategy",
"criteria": {
"pass": "Bypass inspection",
"js_challenge": "Issue Silent JS Proof-of-Work",
"captcha": "Serve Interactive Verification",
"blackhole": "BGP Anycast Blackhole"
}
},
"anomaly_level": {
"type": "score",
"text": "Traffic anomaly scale",
"criteria": ["Nominal", "Elevated", "Volumetric Attack", "Infrastructure Threat"]
}
}
},
"financial_risk": {
"title": "High-Frequency Financial Risk Evaluator",
"description": "Instant fraud scoring and transaction clearance without LLM hallucinations",
"default_state": {"amount": 25000, "user_trust_score": 0.45, "device_anomaly": True, "velocity": 8},
"default_questions": {
"approve_transfer": {"type": "noul", "text": "Approve transaction immediately?"},
"action": {
"type": "choice",
"text": "Payment gateway routing",
"criteria": {
"instant_clearing": "Instant STP Clearing",
"mfa_verify": "Step-up Multi-Factor Authentication",
"manual_hold": "Fraud Queue Manual Review",
"immediate_block": "Immediate Account Block"
}
},
"risk_index": {
"type": "score",
"text": "Financial exposure score",
"criteria": ["Safe", "Moderate", "High Exposure", "Definite Fraud"]
}
}
},
"robotics_industrial": {
"title": "Autonomous Robotics & Industrial Safety Guard",
"description": "Real-time mechanical torque, thermal anomaly, and emergency stop interlock",
"default_state": {"joint_torque_nm": 98.4, "temp_celsius": 82.0, "vibration_g": 2.4, "proximity_m": 0.35},
"default_questions": {
"continue_operation": {"type": "noul", "text": "Is actuator state safe for continuous trajectory?"},
"safety_protocol": {
"type": "choice",
"text": "Motor controller command",
"criteria": {
"nominal_run": "Nominal Kinematic Velocity",
"torque_derate": "Derate Torque 40%",
"controlled_halt": "Controlled Deceleration to Standstill",
"hard_estop": "Trigger Hard Hardware E-STOP"
}
},
"hazard_level": {
"type": "score",
"text": "Mechanical structural stress score",
"criteria": ["Normal Operation", "Elevated Strain", "Warning Limit", "Critical Failure Risk"]
}
}
},
"ecommerce_fraud": {
"title": "E-Commerce Checkout Fraud Guard",
"description": "Checkout cart velocity, shipping delta, and stolen card protection",
"default_state": {"cart_value": 1400, "shipping_billing_mismatch": True, "card_attempts": 3},
"default_questions": {
"allow_checkout": {"type": "noul", "text": "Allow order placement?"},
"verification_tier": {
"type": "choice",
"text": "Checkout challenge tier",
"criteria": {
"seamless": "Frictionless 1-Click Order",
"3ds_secure": "Trigger 3D Secure 2.0 Challenge",
"manual_hold": "Hold Order for Verification",
"void_transaction": "Decline and Flag Cardholder"
}
},
"risk_score": {
"type": "score",
"text": "Cart risk index",
"criteria": ["Low Risk", "Medium", "Suspicious", "High Fraud Likelihood"]
}
}
}
}
# -----------------------------------------------------------------------------
# App, CORS, security middleware
# -----------------------------------------------------------------------------
@asynccontextmanager
async def lifespan(app: FastAPI):
t0 = time.perf_counter()
DEFAULT_ROUTER.decide(state={"warmup": True}, questions={"ready": werr.NoulQuestion("System ready?")})
PK.evaluate({"tool_name": "read_status"}, BUILTIN_GATES["agent_mcp_guard"])
try:
CS.init()
threading.Thread(target=_housekeeping, daemon=True).start()
except Exception as e:
print("[answerr] commerce store unavailable:", e, file=sys.stderr)
print("[answerr] API {} ready in {:.1f} ms; {} built-in gates, {} tenant gates, {} API keys, reCAPTCHA {}".format(
API_VERSION, (time.perf_counter() - t0) * 1000, len(BUILTIN_GATES), GATE_STORE.count(),
len(API_KEYS), "on" if RECAPTCHA_SECRET else "off"))
yield
def _housekeeping():
"""Hourly retention purge (idempotent; every worker may run it)."""
while True:
time.sleep(3600)
try:
CS.purge()
except Exception as e:
print("[answerr] purge failed:", e, file=sys.stderr)
app = FastAPI(
title="answerr Decision API",
description="Deterministic decision policies written in natural language, compiled to explicit rules, "
"executed with a full trace. ITouch Bilişim Sistemleri Ltd. Şti.",
version=API_VERSION,
lifespan=lifespan,
docs_url="/v1/docs",
redoc_url="/v1/redoc",
openapi_url="/v1/openapi.json",
)
@app.exception_handler(CS.CommerceError)
async def _commerce_error(request: Request, exc: CS.CommerceError):
return CROUTER.error_response(exc)
app.add_middleware(
CORSMiddleware,
allow_origins=["https://answerr.me", "https://www.answerr.me", "https://api.answerr.me",
"https://pcworm.github.io", "http://localhost:3000", "http://localhost:8000",
"http://127.0.0.1:8000", "http://127.0.0.1:5500"],
allow_origin_regex=r"https://([a-z0-9-]+\.)?answerr\.me",
allow_credentials=False,
allow_methods=["GET", "POST", "PATCH", "DELETE", "OPTIONS"],
allow_headers=["Content-Type", "Authorization", "Accept", "X-Requested-With", "X-API-Key", "X-Recaptcha-Token", "X-Admin-Key"],
expose_headers=["X-RateLimit-Limit", "X-RateLimit-Remaining", "Retry-After", "X-Answerr-Verdict", "X-Answerr-Policy-Seal",
"X-Answerr-Decision-Id", "X-Answerr-Quota-Remaining", "Content-Disposition"],
max_age=86400,
)
@app.middleware("http")
async def security_middleware(request: Request, call_next):
from starlette.concurrency import run_in_threadpool
if request.method == "OPTIONS":
return await call_next(request)
if request.method in ("POST", "PUT", "PATCH"):
cl = request.headers.get("content-length")
if cl is None:
return JSONResponse(status_code=411, content={"status": "error", "error": "Length Required"})
try:
if int(cl) > MAX_REQUEST_BODY_BYTES:
return JSONResponse(status_code=413, content={
"status": "error", "error": "Payload Too Large",
"message": "Request body exceeds {} bytes.".format(MAX_REQUEST_BODY_BYTES)})
except ValueError:
return JSONResponse(status_code=400, content={"status": "error", "error": "Bad Content-Length"})
ip = client_ip(request)
tenant, principal = await run_in_threadpool(authenticate_principal, request)
recaptcha = "absent"
if tenant:
tier, ident = "api_key", "tenant:" + tenant
else:
token = request.headers.get("x-recaptcha-token")
if token:
recaptcha = await run_in_threadpool(verify_recaptcha, token, ip)
tier = "verified" if recaptcha == "verified" else "anonymous"
ident = "ip:" + ip
request.state.security = {"tenant": tenant, "rate_tier": tier, "recaptcha": recaptcha, "principal": principal}
remaining = None
limit = SlidingWindowLimiter.TIERS[tier][0]
if request.url.path not in ("/health", "/v1/health", "/v1/docs", "/v1/redoc", "/v1/openapi.json"):
ok, limit, remaining, retry = LIMITER.check(ident, tier)
if ok and not tenant and not via_iis(request) and (request.client and request.client.host in TRUSTED_PROXIES):
ok, _, _, retry = LIMITER.check("direct", "direct_shared")
if not ok:
return JSONResponse(status_code=429, headers={
"X-RateLimit-Limit": str(limit), "X-RateLimit-Remaining": "0", "Retry-After": str(retry)},
content={"status": "error", "error": "Too Many Requests", "rate_tier": tier,
"retry_after_seconds": retry})
response: Response = await call_next(request)
response.headers["X-RateLimit-Limit"] = str(limit)
if remaining is not None:
response.headers["X-RateLimit-Remaining"] = str(remaining)
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-Frame-Options"] = "DENY"
response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
response.headers["Permissions-Policy"] = "geolocation=(), camera=(), microphone=()"
if not request.url.path.startswith(("/v1/docs", "/v1/redoc")):
response.headers["Cache-Control"] = "no-store"
response.headers["Server"] = "answerr"
return response
def _security(request: Request) -> Dict[str, Any]:
return getattr(request.state, "security", {"tenant": None, "rate_tier": "anonymous", "recaptcha": "absent", "principal": None})
# -----------------------------------------------------------------------------
# Schemas
# -----------------------------------------------------------------------------
ALLOWED_OPS = {">", ">=", "<", "<=", "==", "=", "!=", "in", "not_in", "has_token"}
ALLOWED_EFFECTS = {"ALLOW", "DENY", "REVIEW"}
class QuestionSpec(BaseModel):
type: str = Field("noul", description="'noul', 'choice' or 'score'")
text: Optional[str] = None
instructions: Optional[str] = None
threshold: Optional[float] = 0.5
criteria: Optional[Union[Dict[str, str], List[str]]] = None
@property
def resolved_text(self) -> str:
return (self.text or self.instructions or "Is the proposed operation safe and valid?").strip()
class WerrParamsSpec(BaseModel):
"""Full werr v0.5.1 parameter configuration (auto/preset or explicit overrides)."""
preset: Optional[str] = Field(
None,
description="'auto' (default, purpose-aligned by gate/domain), 'smart_router', 'security_guard', "
"'risk_evaluator', 'crown_core', or 'universal_cusp'"
)
mode: Optional[str] = Field(None, description="'hybrid', 'lexical', 'resonance', or 'pure_fractal'")
domain_mode: Optional[str] = Field(None, description="'multi' or 'none'")
enable_domain: Optional[bool] = Field(None, description="Axis 1 of 8-state cube: Multi-Domain Gate routing")
enable_lexical: Optional[bool] = Field(None, description="Axis 2 of 8-state cube: Exact keyword anchoring")
enable_resonance: Optional[bool] = Field(None, description="Axis 3 of 8-state cube: 4-stem & Mandelbrot pole resonance")
tripod: Optional[bool] = Field(None, description="3-point triangular probe for dynamic fused escape velocity")
cadence_lambda: Optional[float] = Field(None, ge=0.0, le=2.0, description="Trajectory cadence coupling (lambda)")
cadence_beta: Optional[float] = Field(None, ge=0.0, le=2.0, description="Boundary damping factor (beta)")
cadence_alpha: Optional[float] = Field(None, ge=0.0, le=1.0, description="Resonance blending weight (alpha)")
temp_choice: Optional[float] = Field(None, ge=0.05, le=10.0, description="Softmax temperature for 4-quadrant choice")
resolution: Optional[int] = Field(None, ge=8, le=128, description="Manifold sampling resolution")
max_iter: Optional[int] = Field(None, ge=8, le=256, description="Mandelbrot escape iteration ceiling")
cx: Optional[float] = Field(None, ge=-5.0, le=5.0, description="24B seed real coordinate (c_x)")
cy: Optional[float] = Field(None, ge=-5.0, le=5.0, description="24B seed imaginary coordinate (c_y)")
zoom: Optional[float] = Field(None, ge=0.01, le=1000000.0, description="24B seed magnification factor (zoom)")
auto_route: Optional[bool] = Field(None, description="Force automatic domain routing on/off")
preferred_domain: Optional[str] = Field(None, description="Preferred domain gate key")
telemetry_opt_in: Optional[bool] = Field(None, description="Opt in/out of anonymous open-science telemetry")
WERR_PRESETS: Dict[str, Dict[str, Any]] = {
"smart_router": {
"id": "smart_router",
"title_tr": "Akıllı Yönlendirici (Dengeli 4-Kadran · [1,1,1])",
"title_en": "Smart Router (Balanced 4-Quadrant · [1,1,1])",
"purpose_tr": "AI ajan araç kapıları (agent_mcp_guard) ve çok alanlı genel karar orkestrasyonu için en ideal kurgu.",
"purpose_en": "Optimal for AI agent action gates (agent_mcp_guard) and multi-domain decision orchestration.",
"cx": -0.10109636384562,
"cy": 0.95628651080914,
"zoom": 45.0,
"mode": "hybrid",
"domain_mode": "multi",
"enable_domain": True,
"enable_lexical": True,
"enable_resonance": True,
"tripod": True,
"cadence_lambda": 0.10,
"cadence_beta": 0.15,
"cadence_alpha": 0.50,
"temp_choice": 1.25,
"resolution": 36,
"max_iter": 36,
"preferred_domain": "api_security",
},
"security_guard": {
"id": "security_guard",
"title_tr": "Sıfır Güven Kalkanı (Seahorse Vadisi Keskin Sınır · [1,1,1])",
"title_en": "Zero-Trust Security Guard (Seahorse Valley Sharp Boundary · [1,1,1])",
"purpose_tr": "API güvenlik duvarı (api_zero_trust_waf), DDoS engelleme ve yüksek hassasiyetli erişim denetimi için en ideal kurgu.",
"purpose_en": "Optimal for zero-trust API WAF (api_zero_trust_waf), DDoS mitigation, and high-sensitivity access control.",
"cx": -0.7436438870371587,
"cy": 0.1318259042053119,
"zoom": 120.0,
"mode": "hybrid",
"domain_mode": "multi",
"enable_domain": True,
"enable_lexical": True,
"enable_resonance": True,
"tripod": True,
"cadence_lambda": 0.08,
"cadence_beta": 0.12,
"cadence_alpha": 0.60,
"temp_choice": 1.00,
"resolution": 36,
"max_iter": 48,
"preferred_domain": "api_security",
},
"risk_evaluator": {
"id": "risk_evaluator",
"title_tr": "Finansal Risk Değerlendirici (Yumuşak Gradyan · [1,1,1])",
"title_en": "Financial Risk Evaluator (Smooth Gradient · [1,1,1])",
"purpose_tr": "Ödeme, 3D Secure ve e-ticaret dolandırıcılık puanlaması (fintech_payment_tr) için sürekli kaçış gradyanlı kurgu.",
"purpose_en": "Optimal for payment risk, 3D Secure and checkout fraud scoring (fintech_payment_tr) with smooth escape gradients.",
"cx": -0.75,
"cy": 0.10,
"zoom": 25.0,
"mode": "hybrid",
"domain_mode": "multi",
"enable_domain": True,
"enable_lexical": True,
"enable_resonance": True,
"tripod": True,
"cadence_lambda": 0.12,
"cadence_beta": 0.18,
"cadence_alpha": 0.55,
"temp_choice": 1.10,
"resolution": 36,
"max_iter": 48,
"preferred_domain": "financial_risk",
},
"crown_core": {
"id": "crown_core",
"title_tr": "Crown Core · Periyot-3 Üçayak Rezonansı ([1,1,1])",
"title_en": "Crown Core · Period-3 Tripod Resonance ([1,1,1])",
"purpose_tr": "Endüstriyel robotik güvenlik, IoT emniyet kilidi ve Werracle Z/9Z rezonans uyumlu donanım refleksi.",
"purpose_en": "Optimal for industrial robotics safety, IoT interlocks, and Werracle Z/9Z resonant hardware reflexes.",
"cx": -0.1225611668766536,
"cy": 0.7448617666197442,
"zoom": 64.0,
"mode": "hybrid",
"domain_mode": "multi",
"enable_domain": True,
"enable_lexical": True,
"enable_resonance": True,
"tripod": True,
"cadence_lambda": 0.10,
"cadence_beta": 0.15,
"cadence_alpha": 0.50,
"temp_choice": 1.00,
"resolution": 48,
"max_iter": 64,
"preferred_domain": "iot_safety",
},
"universal_cusp": {
"id": "universal_cusp",
"title_tr": "Saf Fraktal · Evrensel Cusp ([0,0,0] · Sıfır Sözlük)",
"title_en": "Pure Fractal · Universal Cusp ([0,0,0] · Zero Ontology)",
"purpose_tr": "Alan sözlüklerini kapatarak yalnızca 16B durum vektörünün 24-bayt Mandelbrot sınırındaki (∂M) saf geometrik yörüngesini çalıştırır.",
"purpose_en": "Locks domain ontologies off and evaluates pure 16D state projection on the 24-byte Mandelbrot boundary (∂M).",
"cx": -0.7436438870371587,
"cy": 0.1318259042053119,
"zoom": 50.0,
"mode": "pure_fractal",
"domain_mode": "none",
"enable_domain": False,
"enable_lexical": False,
"enable_resonance": False,
"tripod": True,
"cadence_lambda": 0.10,
"cadence_beta": 0.15,
"cadence_alpha": 0.50,
"temp_choice": 1.25,
"resolution": 36,
"max_iter": 36,
"preferred_domain": None,
},
}
GATE_WERR_PROFILES: Dict[str, str] = {
"agent_mcp_guard": "smart_router",
"fintech_payment_tr": "risk_evaluator",
"api_zero_trust_waf": "security_guard",
"api_security": "security_guard",
"ddos_mitigation": "security_guard",
"financial_risk": "risk_evaluator",
"ecommerce_fraud": "risk_evaluator",
"robotics_industrial": "crown_core",
"iot_safety": "crown_core",
"game_combat": "smart_router",
}
class DecisionRequest(BaseModel):
state: Optional[Dict[str, Any]] = Field(default_factory=dict)
domain: Optional[str] = None
gate_id: Optional[str] = None
policy: Optional[Dict[str, Any]] = Field(None, description="Inline draft policy (not stored)")
strict_policy: Optional[bool] = False
questions: Optional[Dict[str, QuestionSpec]] = None
question: Optional[str] = None
prompt: Optional[str] = None
recaptcha_token: Optional[str] = None
mode: Optional[str] = Field(None, description="'live' (default) or 'shadow': logged and metered, never queued for review")
observed_outcome: Optional[Any] = Field(None, description="Your own decision for this case (ALLOW/REVIEW/DENY or true/false), for shadow reports")
external_id: Optional[str] = Field(None, max_length=120, description="Your reference (order id, tool-call id); echoed in logs, reviews and webhooks")
enqueue_review: Optional[bool] = Field(True, description="REVIEW verdicts go to the human-review queue (Pro and above)")
cx: Optional[float] = None
cy: Optional[float] = None
zoom: Optional[float] = None
werr_preset: Optional[str] = Field(None, description="Pre-calibrated werr profile ('auto', 'smart_router', 'security_guard', 'risk_evaluator', 'crown_core', 'universal_cusp')")
werr_params: Optional[WerrParamsSpec] = Field(None, description="Full werr engine parameter overrides")
class HardRuleSpec(BaseModel):
id: str = Field(..., min_length=1, max_length=80)
field: str = Field(..., min_length=1, max_length=64)
op: str
value: Any
effect: str = "DENY"
reason: Optional[str] = Field(None, max_length=500)
class PolicyGateCreateRequest(BaseModel):
gate_id: str
version: str = "1.0.0"
title: str = Field("Custom policy", max_length=120)
category: str = Field("Custom Policy", max_length=60)
unknown_fallback: str = "abstain_review"
fields: List[str] = Field(default_factory=list)
required_fields: List[str] = Field(default_factory=list)
field_aliases: Dict[str, List[str]] = Field(default_factory=dict)
hard_rules: List[HardRuleSpec] = Field(default_factory=list)
feature_weights: Dict[str, Dict[str, float]] = Field(default_factory=dict)
tool_policy: Optional[Dict[str, str]] = None
source_prompt: Optional[str] = Field(None, max_length=4000)
class PolicyCompileRequest(BaseModel):
prompt: str = Field(..., min_length=3, max_length=4000)
gate_id: Optional[str] = "draft_policy"
domain: Optional[str] = None
schema_fields: Optional[List[str]] = None
sample_state: Optional[Dict[str, Any]] = None
class ChatMessage(BaseModel):
role: str
content: str
class ChatCompletionRequest(BaseModel):
model: Optional[str] = "werr-reflex-v1"
messages: List[ChatMessage]
temperature: Optional[float] = 0.0
max_tokens: Optional[int] = 512
domain: Optional[str] = None
state: Optional[Dict[str, Any]] = None
werr_preset: Optional[str] = None
werr_params: Optional[WerrParamsSpec] = None
def validate_policy(p: Dict[str, Any]) -> Dict[str, Any]:
"""Normalizes an inline or registered policy and rejects malformed ones."""
if not isinstance(p, dict):
raise HTTPException(400, "policy must be an object")
rules = p.get("hard_rules") or p.get("hardRules") or []
if not isinstance(rules, list) or len(rules) > MAX_RULES:
raise HTTPException(400, "hard_rules must be a list of at most {} rules".format(MAX_RULES))
clean_rules = []
for r in rules:
if not isinstance(r, dict):
raise HTTPException(400, "each rule must be an object")
op = r.get("op")
eff = str(r.get("effect", "DENY")).upper()
if op not in ALLOWED_OPS:
raise HTTPException(400, "unsupported op '{}'".format(op))
if eff not in ALLOWED_EFFECTS:
raise HTTPException(400, "unsupported effect '{}'".format(eff))
if not isinstance(r.get("field"), str) or not r["field"] or len(r["field"]) > 64:
raise HTTPException(400, "rule field must be a non-empty string")
clean_rules.append({"id": str(r.get("id") or ("rule_" + r["field"]))[:80], "field": r["field"], "op": op,
"value": r.get("value"), "effect": eff, "reason": (r.get("reason") or None)})
tool_policy = p.get("tool_policy") or p.get("toolPolicy")
if tool_policy is not None:
if not isinstance(tool_policy, dict) or any(str(v).upper() not in ALLOWED_EFFECTS for v in tool_policy.values()):
raise HTTPException(400, "tool_policy values must be ALLOW, DENY or REVIEW")
tool_policy = {k: str(v).upper() for k, v in tool_policy.items()}
out = {
"gate_id": str(p.get("gate_id") or p.get("id") or "inline_policy")[:64],
"version": str(p.get("version") or "1.0.0")[:32],
"unknown_fallback": p.get("unknown_fallback") or p.get("unknownFallback") or "abstain_review",
"fields": [str(f)[:64] for f in (p.get("fields") or [])][:200],
"required_fields": [str(f)[:64] for f in (p.get("required_fields") or p.get("requiredFields") or [])][:50],
"field_aliases": {str(k)[:64]: [str(a)[:64] for a in (v or [])][:20]
for k, v in (p.get("field_aliases") or p.get("fieldAliases") or {}).items()},
"hard_rules": clean_rules,
"feature_weights": p.get("feature_weights") or p.get("featureWeights") or {},
}
if tool_policy is not None:
out["tool_policy"] = tool_policy
for k in ("title", "category", "source_prompt"):
if p.get(k):
out[k] = str(p[k])[:4000]
return out