"
def page(sec, body):
n1, n2 = NEBULAS.get(sec, ("rgba(120,85,255,.16)", "rgba(0,190,255,.10)"))
uid = current_user_id()
acct = ""
if uid:
try:
con = db()
u = con.execute("SELECT username FROM users WHERE id=?", (uid,)).fetchone()
bal = get_balance(uid)
pas = has_pass(uid)
acct = (''
+ ("★ PASS · " if pas else "") + "◈ $" + f"{bal/100:.2f}" + " · " + esc(u["username"]) + ""
+ ' EXIT')
except Exception:
acct = ""
if not uid or not acct:
nxt = ("?next=" + urllib.parse.quote(request.path)) if request.path not in ("/", "/inbox", "/signup", "/logout") else ""
acct = ('LOG IN'
' SIGN UP')
from markupsafe import Markup
st = get_settings(uid)
return render_template_string(BASE, body=Markup(body), bmac=BMAC, o=lambda s2: "on" if s2 == sec else "",
n1=n1, n2=n2, acct=Markup(acct),
CFG_JS="window.DRB=" + json.dumps(st) + ";")
def _checkout_or_json(payload):
"""If a browser form POSTed (no JSON accept / no X-Requested-With), redirect to
the BTCPay checkout page instead of showing raw JSON."""
wants_html = "text/html" in (request.headers.get("Accept") or "") and "application/json" not in (request.headers.get("Accept") or "")
link = payload.get("checkoutLink") if isinstance(payload, dict) else None
if wants_html and link:
return Redirect(link)
return jsonify(payload)
def Redirect(u):
from flask import redirect as _r
return _r(u)
def agent_card(endpoint, example, notes):
"""Interactive-for-LLMs card: exact curl + auth + link to openapi."""
return ('
')
def gloss(terms):
chips = " ".join('' + esc(t) + '' for t, d in terms)
return '
JARGON — hover any chip:
' + chips + '
'
def how(steps):
lis = "".join(f"
{esc(s)}
" for s in steps)
return f'
HOW IT WORKS{lis}
'
def flow(title, steps):
"""Concrete example flow: numbered scene-by-scene walkthrough with role chips."""
lis = "".join(f"
{s}
" for s in steps) # steps carry their own / markup
return f'
EXAMPLE FLOW — {esc(title)}{lis}
'
# ---------- AGENT DISCOVERY ----------
LLMS_SETTINGS = """
## ACCOUNT TUNABLES (machine-settable)
GET/POST /api/settings — keys: bg, warp, parallax, density (0-2.5), speed (0-3), twinkle (0-3), hue (-180-180), grid, scan, toast, type (1|0).
Agents driving browsers (or building clients) can persist a theme per API key: POST form-encoded key=value. Values validated server-side.
## KEYBOARD
Ctrl+K / Cmd+K — command palette on any page. Type tool name, Enter navigates.
"""
API_INDEX = {
"service": "dark0rbits",
"description": "IP intel, card BIN validation, 30-min SMS rentals, residential proxy lab, steganography, trackable files, no-KYC messaging, utilities.",
"endpoints": [
{"method": "GET", "path": "/signup", "desc": "No-KYC signup page (humans): username + password, 4+ chars, ~10 seconds. Agents: POST /inbox form act=register&u=NAME&p=PASS -> session cookie dark0rbits_tok (30 days) + $1 free trial credit."},
{"method": "GET/POST", "path": "/api/settings", "desc": "Per-account UI tunables (bg, warp, parallax, density, speed, twinkle, hue, grid, scan, toast, type). Agents can theme their own client. GET returns current; POST form key=val applies (validated + clamped)."},
{"method": "GET", "path": "/deaddrop", "desc": "Burn-after-read encrypted notes. POST /api/deaddrop/create (body, burn_after 1-10, ttl_hours 1-72, password optional) -> token. FREE."},
{"method": "GET", "path": "/shot", "desc": "Page capture: POST /api/shot/create {url} then GET /api/shot/status/. SSRF-guarded. FREE."},
{"method": "GET", "path": "/score", "desc": "Composite fraud score: IP 45% + disposable-email 25% + BIN 30%. FREE."},
{"method": "GET", "path": "/api/ip?target=", "desc": "Caller IP intel (auto) or any IP you pass: geo, ASN, ISP, VPN/hosting flags, rDNS."},
{"method": "GET", "path": "/api/phone?num=", "desc": "Phone OSINT: validity, country, region, carrier, line type (mobile/landline/voip), timezones, risk flags + free deep-dive lead links. Any format."},
{"method": "GET", "path": "/api/user?u=", "desc": "Username OSINT: probes 16 platforms in parallel (GitHub, Reddit, Telegram, Steam…) → per-site found/not-found/unknown + lead links."},
{"method": "GET", "path": "/api/domain?d=", "desc": "Domain OSINT: RDAP registration (registrar/dates/status), full DNS (A/AAAA/MX/NS/TXT/CNAME via DoH), certificate-transparency subdomains. Passive."},
{"method": "POST", "path": "/api/forensics", "files": ["image"], "desc": "Deep image forensics: all EXIF IFDs, decoded GPS + map links, XMP, embedded thumbnail, hashes, editor flags, ELA verdict."},
{"method": "POST", "path": "/api/card", "params": {"num": "card number"}, "desc": "Luhn + BIN intel. Nothing stored/charged."},
{"method": "POST", "path": "/api/sms/rent", "params": {"service": "id/keyword", "country": "id"}, "desc": "Rent disposable number, 30 min, refundable."},
{"method": "GET", "path": "/api/sms/check?pid=", "desc": "Poll SMS code."},
{"method": "GET", "path": "/api/sms/cancel?pid=", "desc": "Cancel + refund."},
{"method": "GET", "path": "/api/sms/history", "desc": "Rental history."},
{"method": "POST", "path": "/api/proxy/test", "params": {"user": "Pleiades user", "pass": "password"}, "desc": "Tunnel CONNECT via Pleiades gateway, return egress IP/geo."},
{"method": "POST", "path": "/api/steg/hide", "params": {"image": "png file", "text": "secret", "password": "optional", "bits": "1-3", "spread": "sequential|random"}, "desc": "LSB steganography → PNG download."},
{"method": "POST", "path": "/api/steg/extract", "params": {"image": "png file", "password": "optional"}, "desc": "Extract hidden text."},
{"method": "POST", "path": "/api/track/create", "params": {"filename": "name"}, "desc": "Create free trackable file. Returns upload_url + token. Login required (POST /inbox act=register)."},
{"method": "GET", "path": "/api/track/events?token=", "desc": "Open events for a trackable (auth via account)."},
{"method": "GET", "path": "/api/hash?s=", "desc": "md5/sha1/sha256/sha512."},
{"method": "GET", "path": "/api/hdr?url=", "desc": "Fetch URL, return status + headers."},
{"method": "POST", "path": "/api/deaddrop/create", "params": {"body": "note text (max 8000 chars)", "burn_after_reads": "1-10", "ttl_hours": "1-72", "password": "optional"}, "desc": "AES-GCM encrypted burn-after-read note. Returns /drop/ URL. FREE. Reads decrement; note self-destructs at 0 or at TTL."},
{"method": "GET", "path": "/drop/", "desc": "Read a dead-drop (password-protected if set). Each view burns one read."},
{"method": "POST", "path": "/api/shot/create", "params": {"url": "http(s):// target"}, "desc": "Screenshot queue. Headless Chromium PNG if available, else rendered-text capture (status=text_fallback). FREE. Poll /api/shot/status/."},
{"method": "GET", "path": "/api/shot/status/", "desc": "Shot result: base64 PNG (png_b64) or text preview + page intel."},
{"method": "GET", "path": "/dms", "desc": "Dead man switch: arm switches with pre-written payload messages; check in via curl or they seal as burn-after-read dead-drops when the window lapses. FREE."},
{"method": "POST", "path": "/api/dms/create", "desc": "Arm a switch: label, interval_hours (24/48/72/168), 1-5 payloads, optional custodian note. Returns token + checkin_url. Auth: session or Bearer key."},
{"method": "GET", "path": "/api/dms/list", "desc": "List your switches with status ARMED/LATE/TRIGGERED and drop URLs after trigger. Auth required."},
{"method": "POST", "path": "/api/dms/checkin?token=", "desc": "Check in (no auth, token IS the key) -> 200 'checked in'. Resets the window. Missing the window seals payloads as /drop/ links."},
{"method": "POST", "path": "/chain", "desc": "Create a custody chain. Form: name. Login required."},
{"method": "POST", "path": "/chain/add", "desc": "Append an entry to a chain. Form: log (id), data. Login required. 60/min."},
{"method": "GET", "path": "/chain/export?log=", "desc": "Portable JSON receipt with seed, all entries, hashes and verification verdict. Login required."},
{"method": "GET", "path": "/api/chain/list", "desc": "Your chains with link counts and integrity verdicts. Login required."},
{"method": "GET", "path": "/api/chain/entries?log=&verify=1", "desc": "Full entry list for a chain; verify=1 adds verified, links, first_bad_seq. Login required."},
{"method": "POST", "path": "/api/ghost/encode", "desc": "Embed a secret in zero-width characters between words of cover text (cover, secret, password optional). Carrier looks identical to the cover. 60/min."},
{"method": "POST", "path": "/api/ghost/decode", "desc": "Extract hidden message from text (text, password optional). 60/min."},
{"method": "GET", "path": "/api/chaff?seed=", "desc": "Deterministic fake persona from a seed passphrase: name, usernames, birthdate, email pattern, password format, consistent security answers, avatar. Same seed = same persona. Stateless — nothing stored. region=US|UK|DE|NL|XX, domain= for email."},
{"method": "POST", "path": "/api/tracer/case", "desc": "Create a leak-tracing case: per-recipient invisible zero-width watermarks on document text. name, text, recipients=a,b,c. Returns case_id + watermarked variants. Login."},
{"method": "GET", "path": "/api/tracer/identify?case_id=&text=", "desc": "Identify which recipient leaked: paste leaked fragment, get leaker + confidence. Login."},
{"method": "POST", "path": "/api/traceout/run", "params": {"target": "domain or IPv4", "port": "dns|http|https|ssh", "maxhops": "1-30", "timeout": "0.3-5 s"}, "desc": "Hop-by-hop path trace from this host: per-hop IP, rDNS, rtt, geo. FREE."},
{"method": "GET", "path": "/api/traceout/history?limit=", "desc": "Your recent trace runs: target, resolved IP, hop count, complete flag."},
{"method": "POST", "path": "/api/tchain/create", "desc": "Arm a breadcrumb trap chain: nhops (2-8) tripwire URLs where each hop's decoy note carries the next hop. Fires inbox alerts with geo per hop + summary when fully burned. Login."},
{"method": "GET", "path": "/api/tchain/status?chain_id=", "desc": "Per-hop chain state: seq, fired, timestamp, IP. Login."},
{"method": "GET", "path": "/api/score?ip=&email=&bin=", "desc": "Composite fraud score 0-100 + weighted breakdown: IP intel (VPN/hosting/abuse geo), disposable-email domain, BIN country/type risk. FREE."},
{"method": "POST", "path": "/canary", "desc": "Create canary trap. Form: tag, kind (link|pixel|cred|file), rearm (0|1). Login required. Link = /c/, pixel = /c/.png, honeyfile = /c//download, credential returned by /api/canary/list."},
{"method": "GET", "path": "/api/canary/list", "desc": "Your traps with hit counts, links, generated honeytoken credentials. Login required."},
{"method": "GET", "path": "/api/canary/hits?token=", "desc": "Full hit log for a trap: ts, ip, ua, lang, ref + geolocated city/ISP/VPN flags per hit. Login required."},
{"method": "POST", "path": "/api/eh", "desc": "Email header forensics v2: origin IP (+source), origin_geo, hop chain, per-hop relay delays (delays), SPF/DKIM/DMARC verdicts, spoof flags. Handles pasted headers or .eml content. FREE 20/min."},
],
"payment": "EVERYTHING IS FREE — the lab absorbs all costs (SMS rentals, mail, trackables, screenshots). No top-ups needed.",
}
@app.route("/api/settings", methods=["GET", "POST"])
def api_settings():
uid = key_user() or current_user_id()
if not uid:
return jsonify({"ok": False, "error": "auth required: account session or API key"}), 401
if request.method == "GET":
return jsonify({"ok": True, "settings": get_settings(uid)})
out = {}
for k in DEFAULT_SETTINGS:
if k in request.form:
out[k] = set_setting(uid, k, request.form[k])
return jsonify({"ok": True, "applied": out, "settings": get_settings(uid)})
@app.route("/api")
def api_index(): return jsonify(API_INDEX)
@app.route("/robots.txt")
def robots(): return "User-agent: *\nAllow: /\nSitemap: https://dark0rbits.thetempleofdoom.com/sitemap.xml\n", 200, {"Content-Type": "text/plain"}
@app.route("/a8f3dark0rbitskey.txt")
def indexnow_key(): return "a8f3d4rk0rbits9e2b1c7x5k8m2v4q6t8", 200, {"Content-Type": "text/plain"}
INDEXNOW = "a8f3d4rk0rbits9e2b1c7x5k8m2v4q6t8"
@app.route("/sitemap.xml")
def sitemap():
S = "https://dark0rbits.thetempleofdoom.com"
pages = ["", "ip", "card", "sms", "proxy", "steg", "track", "eh", "forensics", "phone", "user", "domain", "canary", "deaddrop", "shot", "score", "mail", "inbox", "passport", "pass", "keys", "maglab", "tools", "signup", "dms"]
xml = '' + "".join(f"{S}/{p}weekly" for p in pages) + ""
return xml, 200, {"Content-Type": "application/xml"}
@app.route("/llms.txt")
def llms():
eps = "\n".join(f"- `{e['method']} {e['path']}` — {e['desc']}" for e in API_INDEX["endpoints"])
return f"# Dark0rbits\n\nBase: {SITE}\n\n## API\n{eps}\n{LLMS_SETTINGS}", 200, {"Content-Type": "text/plain"}
@app.route("/ai-plugin.json")
def aiplugin():
return jsonify({"name_for_model": "dark0rbits", "schema_version": "v1",
"description_for_model": "IP intelligence, card BIN validation, SMS number rentals, proxy egress testing, LSB steganography, trackable file links with open-notifications, no-KYC site messaging.",
"api": {"type": "openapi", "url": SITE + "/openapi.json"}, "auth": {"type": "none"}, "contact_email": "makemoneys8@proton.me"})
@app.route("/openapi.json")
def openapi():
ps = {"openapi": "3.0.0", "info": {"title": "DARK0RBITS", "version": "2.0.0"}, "paths": {}}
def add(path, method, desc, params=None, req=False, files=None):
item = {"summary": desc}
if files:
item["requestBody"] = {"content": {"multipart/form-data": {"schema": {"type": "object", "properties": {**{k: {"type": "string"} for k, v in (params or {}).items()}, **{f: {"type": "string", "format": "binary"} for f in files}}}}}}
elif params:
if method == "get":
item["parameters"] = [{"name": k, "in": "query", "required": req, "schema": {"type": "string"}} for k in params]
else:
item["requestBody"] = {"content": {"application/x-www-form-urlencoded": {"schema": {"type": "object", "properties": {k: {"type": "string"} for k in params}}}}}
ps["paths"][path] = ps["paths"].get(path, {}) | {method: {"responses": {"200": {"description": "ok"}}, **item}}
add("/api/ip", "get", "IP intel (caller or ?target=)", {"target": "optional IP"})
add("/api/phone", "get", "Phone OSINT: carrier, line type, region, timezones, leads", {"num": "phone number, any format"}, req=True)
add("/api/user", "get", "Username OSINT probe across 16 platforms", {"u": "username"}, req=True)
add("/api/domain", "get", "Domain recon: RDAP + DNS + CT subdomains", {"d": "domain"}, req=True)
add("/api/forensics", "post", "Deep image forensics: EXIF IFDs, GPS decoded, XMP, thumbnail, ELA", files=["image"])
add("/api/card", "post", "Luhn + BIN validation", {"num": "card number"}, req=True)
add("/api/sms/rent", "post", "Rent number 30 min", {"service": "id", "country": "id"}, req=True)
add("/api/sms/check", "get", "Poll SMS code", {"pid": "orderid"}, req=True)
add("/api/sms/cancel", "get", "Cancel + refund", {"pid": "orderid"}, req=True)
add("/api/sms/history", "get", "Rental history")
add("/api/proxy/test", "post", "Test Pleiades gateway creds", {"user": "user", "pass": "pass"}, req=True)
add("/api/steg/hide", "post", "LSB-hide text in PNG", {"text": "secret", "password": "opt"}, req=True, files=["image"])
add("/api/steg/extract", "post", "Extract text from PNG", {"password": "opt"}, files=["image"])
add("/api/track/create", "post", "Create $1 invoice for trackable", {"filename": "name"}, req=True)
add("/api/track/events", "get", "Trackable open events", {"token": "token"}, req=True)
add("/api/hash", "get", "Hashes", {"s": "string"}, req=True)
add("/api/hdr", "get", "HTTP headers", {"url": "url"}, req=True)
add("/api/deaddrop/create", "post", "Encrypted burn-after-read note", {"body": "text", "burn_after_reads": "1-10", "ttl_hours": "1-72", "password": "optional"}, req=True)
add("/drop/{token}", "get", "Read a dead-drop (burns one read)")
add("/api/shot/create", "post", "Queue page capture", {"url": "target url"}, req=True)
add("/api/shot/status/{id}", "get", "Shot result (png_b64 or text_fallback)")
add("/api/score", "get", "Composite fraud score 0-100", {"ip": "opt", "email": "opt", "bin": "opt"})
add("/canary", "post", "Create canary trap (tag, kind, rearm)", {"tag": "label", "kind": "link|pixel|cred|file", "rearm": "0|1"}, req=True)
add("/api/canary/list", "get", "Your traps + hit counts + honeytoken creds")
add("/api/canary/hits", "get", "Full hit log with geo per hit", {"token": "trap token"}, req=True)
add("/api/eh", "post", "Email header forensics v2 (origin, delays, verdicts, flags)", {"raw": "full headers or .eml content"}, req=True)
add("/api/dms/create", "post", "Arm a dead man switch: label, interval_hours 24/48/72/168, 1-5 payloads, optional custodian note. Returns token + checkin curl.", {"label": "switch label", "interval_hours": "24|48|72|168", "payloads": "list of 1-5 messages (or payload1..payload5)", "custodian": "optional encrypted note"}, req=True)
add("/api/dms/list", "get", "List your dead man switches with status ARMED/LATE/TRIGGERED and sealed drop URLs.", None)
add("/api/dms/checkin", "post", "Check in a switch by token (no login needed). 200 'checked in' resets the window.", {"token": "switch token"}, req=True)
add("/chain", "post", "Create a custody chain (name)", {"name": "chain label"}, req=True)
add("/chain/add", "post", "Append an entry to a chain (log, data)", {"log": "chain id", "data": "event text"}, req=True)
add("/chain/export", "get", "Portable JSON receipt of a chain", {"log": "chain id"}, req=True)
add("/api/chain/list", "get", "Your chains + integrity verdicts", None, req=True)
add("/api/chain/entries", "get", "Entries for a chain, optional verification", {"log": "chain id", "verify": "1 to include verdict"}, req=True)
add("/api/ghost/encode", "post", "Zero-width text steganography — embed secret in cover", {"cover": "innocent text", "secret": "hidden message", "password": "optional"}, req=True)
add("/api/ghost/decode", "post", "Extract zero-width hidden message", {"text": "carrier text", "password": "optional"}, req=True)
add("/api/chaff", "get", "Deterministic throwaway persona generator", {"seed": "passphrase", "region": "US|UK|DE|NL|XX", "domain": "email domain"}, req=True)
add("/api/tracer/case", "post", "Leak tracer: watermarked copies per recipient", {"name": "case name", "text": "document text", "recipients": "comma labels"}, req=True)
add("/api/tracer/identify", "get", "Identify the leaker from a fragment", {"case_id": "case", "text": "leaked fragment"}, req=True)
add("/api/tracer/run", "post", "Traceroute from this host to target with per-hop geo", {"target": "domain or IPv4", "port": "dns|http|https|ssh", "maxhops": "1-30", "timeout": "seconds"}, req=True)
add("/api/tracer/history", "get", "Recent traceroute runs for this account", {"limit": "max runs"}, req=False)
add("/api/tchain/create", "post", "Breadcrumb tripwire chain (each trap reveals the next)", {"name": "chain name", "nhops": "2-8"}, req=True)
add("/api/tchain/status", "get", "Trap chain per-hop status", {"chain_id": "chain"}, req=True)
add("/signup", "get", "No-KYC signup page (username + password only)")
return jsonify(ps)
# ---------- 1. IP INTEL (auto + manual target) ----------
def ip_report(ip):
st, b = http(f"http://ip-api.com/json/{ip}?fields=66846719")
d = jf(b) or {}
try: d["reverse"] = d.get("reverse") or socket.gethostbyaddr(ip)[0]
except Exception: pass
return d
@app.route("/ip", methods=["GET", "POST"])
def ip_page():
target = param("target") if request.method == "POST" else param("target")
if target and target.strip():
target = target.strip()
d = ip_report(target)
heading = f"INTEL FOR {esc(target)}"
mine = False
else:
ip = request.headers.get("X-Real-IP") or request.remote_addr or ""
d = ip_report(ip)
heading = "WHAT'S MY IP"
mine = True
if d.get("status") == "fail" or not d:
body = f"
{heading}
lookup failed
{ip_form()}"
return page("ip", body)
rows = [
("IP", f"{esc(d.get('query'))}"),
("Country", f"{esc(d.get('country'))} ({esc(d.get('countryCode'))})"),
("Region / City", f"{esc(d.get('regionName'))} / {esc(d.get('city'))} {esc(d.get('zip'))}"),
("Lat, Lon", f"{d.get('lat')}, {d.get('lon')} · TZ {esc(d.get('timezone'))}"),
("ISP", esc(d.get("isp"))), ("Organization", esc(d.get("org"))), ("AS", esc(d.get("as") or d.get("asname"))),
("Reverse DNS", esc(d.get("reverse") or "—")),
("Flags", f"mobile: {d.get('mobile')} · proxy/VPN: {d.get('proxy')} · hosting: {d.get('hosting')}"),
("Currency", esc(d.get("currency"))),
]
extra = ""
if mine:
hdrs = {k: v for k, v in request.headers.items() if k.lower() in ("user-agent","accept-language","x-forwarded-for","cf-connecting-ip","cf-ipcountry")}
extra = '
Headers you sent
' + "".join(f"
{esc(k)}
{esc(v)}
" for k, v in hdrs.items()) + "
"
body = f"""
{heading}
Auto-detects your IP and shows everything. Want intel on another IP? Type it below — full report, any target.
{kv(rows)}
{extra}
API: GET /api/ip (caller) · GET /api/ip?target=1.2.3.4 (any target)
""" + how(["Your IP is auto-detected the moment the page loads — no input needed.","Type any other IP or hostname into the field for the same full report.","Everything is one GET away for agents: /api/ip and /api/ip?target=.","VPN/proxy/hosting flags come from IP-quality heuristics — if it says proxy, you are looking at a relay."])
body += gloss([("ASN","Autonomous System Number — the network operator that owns this route"),("rDNS","reverse DNS — hostname pointer for an IP"),("hosting","datacenter/cloud IP, not a home connection"),("VPN/proxy","known tunnel or relay range")])
body += agent_card('GET /api/ip?target=1.2.3.4', 'curl "https://dark0rbits.thetempleofdoom.com/api/ip?target=1.2.3.4" -H "Authorization: Bearer drb_..."', 'Auto-detects caller IP if target omitted.')
return page("ip", body)
def ip_form():
return ''
@app.route("/api/ip")
def api_ip():
r = rate_limit("iptarget", 40, 60)
if r: return r
target = param("target")
if target and target.strip():
return jsonify(ip_report(target.strip()))
ip = request.headers.get("X-Real-IP") or request.remote_addr or ""
d = ip_report(ip)
d["headers_seen"] = dict(request.headers)
return jsonify(d)
# ---------- 2. CARD CHECK ----------
def luhn_ok(num):
digits = [int(c) for c in num]
s = sum(digits[-1::-2])
for d in digits[-2::-2]:
d *= 2
if d > 9: d -= 9
s += d
return s % 10 == 0
BRANDS = [("4","Visa"),("51","Mastercard"),("52","Mastercard"),("53","Mastercard"),("54","Mastercard"),("55","Mastercard"),
("22","Mastercard"),("23","Mastercard"),("24","Mastercard"),("25","Mastercard"),("26","Mastercard"),("27","Mastercard"),
("34","Amex"),("37","Amex"),("6011","Discover"),("65","Discover"),("644","Discover"),("645","Discover"),("646","Discover"),("647","Discover"),("648","Discover"),("649","Discover"),
("50","Maestro"),("56","Maestro"),("57","Maestro"),("58","Maestro"),("63","Maestro"),("67","Maestro"),
("30","Diners"),("36","Diners"),("38","Diners"),("39","Diners"),
("35","JCB"),("62","UnionPay"),("7","Mir")]
def brand_of(num):
for pfx, b in BRANDS:
if num.startswith(pfx): return b
return "Unknown"
def bin_lookup(bin8):
st, b = http(f"https://lookup.binlist.net/{bin8}", headers={"Accept-Version": "3"})
bl = jf(b) or {}
if not bl.get("bank") and not bl.get("type") and not bl.get("scheme"):
st, b = http(f"https://data.handyapi.com/bin/{bin8}")
h = jf(b) or {}
if h.get("Status") == "SUCCESS":
return {"bank": {"name": h.get("Issuer")}, "country": {"name": (h.get("Country") or {}).get("Name") if isinstance(h.get("Country"), dict) else h.get("Country")},
"type": str(h.get("Type", "")).lower() or None, "prepaid": "prepaid" in str(h.get("Type","")).lower() or None, "scheme": h.get("Scheme")}
return bl
# ---------- 2b. PHONE LOOKUP (OSINT, offline metadata + free lead links) ----------
def phone_report(raw):
out = {"ok": False}
try:
import phonenumbers as pn
from phonenumbers import carrier as pncarrier, timezone as pntz, geocoder as pngeo
n = pn.parse(raw.strip(), None)
except Exception as e:
out["error"] = f"cannot parse number: {e}"[:200]
return out
out["ok"] = True
out["e164"] = pn.format_number(n, pn.PhoneNumberFormat.E164)
out["national"] = pn.format_number(n, pn.PhoneNumberFormat.NATIONAL)
out["international"] = pn.format_number(n, pn.PhoneNumberFormat.INTERNATIONAL)
out["valid"] = pn.is_valid_number(n)
out["possible"] = pn.is_possible_number(n)
out["country"] = pn.region_code_for_country_code(n.country_code or 0)
try: out["country_calling_code"] = f"+{n.country_code}"
except Exception: pass
try:
out["region_desc"] = pngeo.description_for_number(n, "en") or ""
except Exception: out["region_desc"] = ""
try:
out["carrier"] = pncarrier.name_for_number(n, "en") or ""
except Exception: out["carrier"] = ""
try:
out["timezones"] = list(pntz.time_zones_for_number(n))
except Exception: out["timezones"] = []
tmap = {0:"fixed_line",1:"mobile",2:"fixed_or_mobile",3:"freephone",4:"premium_rate",5:"shared_cost",6:"voip",7:"personal_number",8:"pager",9:"uan",10:"voicemail"}
try:
t = pn.number_type(n)
out["line_type"] = tmap.get(t, "unknown")
out["line_type_risk"] = ("voip/uan numbers are often disposable or bulk-registered" if t in (6, 9) else "")
except Exception: out["line_type"] = "unknown"
q = out["e164"]
out["leads"] = {
"google": "https://www.google.com/search?q=%22" + urllib.parse.quote(q) + "%22",
"duckduckgo": "https://duckduckgo.com/?q=" + urllib.parse.quote(q),
"truecaller": "https://www.truecaller.com/search/" + (out["country"] or "us").lower() + "/" + q.lstrip("+"),
}
if out["line_type"] == "voip": out.setdefault("flags", []).append("voip — high disposable/spoof potential")
if not out["valid"]: out.setdefault("flags", []).append("not a valid number — fake or mistyped")
return out
@app.route("/phone", methods=["GET", "POST"])
def phone_tool():
res = ""
if request.method == "POST":
raw = param("num") or ""
if raw.strip():
d = phone_report(raw)
if d.get("ok"):
res = kv([
("Number", f'{esc(d["e164"])} ({esc(d["national"])})'),
("Valid", 'VALID' if d["valid"] else 'NOT VALID'),
("Country", esc(d["country"]) + " " + esc(d["country_calling_code"])),
("Region", esc(d["region_desc"]) or "—"),
("Carrier", esc(d["carrier"]) or "—"),
("Line type", esc(d["line_type"])),
("Timezones", esc(", ".join(d["timezones"])) or "—"),
])
if d.get("flags"):
res += '
Flags ' + " ".join('' + esc(f) + "" for f in d["flags"]) + "
Parse + intel on any number worldwide: validity, country, region, carrier, line type (mobile/landline/VOIP), timezones — plus free deep-dive lead links. No KYC, no logs.
{res}
API: GET /api/phone?num=%2B14255550100 → JSON: valid, country, region, carrier, line_type, timezones, flags, lead links.
""" + how(["Type the number in any format — country code, spaces, dashes, all handled.",
"Metadata comes from offline libphonenumber data — instant and private, nothing phoned home.",
"Line type matters: VOIP/UAN numbers are the disposable, bulk-registered kind.",
"Follow the lead links for the human layer: public mentions, directory listings, name lookups.",
"Pair it with SMS RENTAL — know the number type before you verify with it."])
body += gloss([("E164","the international standard format: + and country code, no spaces"),("line type","mobile vs landline vs VOIP — carriers publish the ranges"),("VOIP","internet-based number — cheap, disposable, often spoofed")])
body += agent_card('GET /api/phone?num=%2B14255550100', 'curl "https://dark0rbits.thetempleofdoom.com/api/phone?num=%2B14255550100"', 'valid, country, region, carrier, line_type, timezones, flags + free lead links.')
return page("phone", body)
@app.route("/api/phone", methods=["GET", "POST"])
def api_phone():
r = rate_limit("phone", 30, 60)
if r: return r
raw = (param("num") or "").strip()
if not raw: return jsonify({"ok": False, "error": "num required (any format, country code encouraged)"}), 400
return jsonify(phone_report(raw))
# ---------- 2c. USERNAME SLEUTH (OSINT profile probe) ----------
USER_SITES = [
("GitHub", "https://github.com/{u}"),
("GitLab", "https://gitlab.com/{u}"),
("Reddit", "https://www.reddit.com/user/{u}/"),
("Telegram", "https://t.me/{u}"),
("Medium", "https://medium.com/@{u}"),
("Pastebin", "https://pastebin.com/u/{u}"),
("Keybase", "https://keybase.io/{u}"),
("About.me", "https://about.me/{u}"),
("SoundCloud", "https://soundcloud.com/{u}"),
("Vimeo", "https://vimeo.com/{u}"),
("Steam", "https://steamcommunity.com/id/{u}"),
("Last.fm", "https://www.last.fm/user/{u}"),
("Dribbble", "https://dribbble.com/{u}"),
("Imgur", "https://imgur.com/user/{u}"),
("Chess.com", "https://www.chess.com/member/{u}"),
("Twitch", "https://www.twitch.tv/{u}"),
]
def _probe_site(name, url):
st, b = http(url, timeout=10)
if st == 200:
return {"site": name, "url": url, "status": "found", "http": st}
if st == 404:
return {"site": name, "url": url, "status": "not found", "http": st}
return {"site": name, "url": url, "status": "unknown", "http": st, "note": "site blocked or rate-limited the probe — check manually"}
def user_probe(u):
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=8) as ex:
results = list(ex.map(lambda s: _probe_site(s[0], s[1].format(u=urllib.parse.quote(u))), USER_SITES))
found = [r for r in results if r["status"] == "found"]
return {"ok": True, "username": u, "found": found, "results": results,
"hits": len(found), "leads": {
"google": "https://www.google.com/search?q=%22" + urllib.parse.quote(u) + "%22",
"instantusername": "https://instantusername.com/#/" + urllib.parse.quote(u)}}
@app.route("/user", methods=["GET", "POST"])
def user_tool():
res = ""
if request.method == "POST":
u = (param("u") or "").strip()
if u and 2 <= len(u) <= 60 and all(c not in "<>\"'" for c in u):
d = user_probe(u)
rows = "".join(f'
Give it a handle — it probes {len(USER_SITES)} major platforms in parallel and reports where that username lives. Classic OSINT footwork, automated.
{res}
API: GET /api/user?u=NAME → JSON with per-site found/not-found/unknown.
""" + how(["Type the handle — no @, no https, just the name.",
"Sixteen sites get probed at once — GitHub, Reddit, Telegram, Steam and more.",
"FOUND = a live profile answered on that exact URL. Unknown = the site blocked the probe (check manually).",
"Follow the Google/InstantUsername leads for the long tail of smaller platforms.",
"Same handle on multiple sites = the same human. That's the whole point."])
body += gloss([("probe","an HTTP GET that never logs in or scrapes private data"),("handle","the username part of a profile URL"),("correlation","linking profiles across sites by shared handle")])
body += agent_card('GET /api/user?u=somehandle', 'curl "https://dark0rbits.thetempleofdoom.com/api/user?u=somehandle"', 'Per-site found/not-found/unknown + lead links. ~8s, all probes in parallel.')
return page("user", body)
@app.route("/api/user", methods=["GET", "POST"])
def api_user():
r = rate_limit("user", 10, 60)
if r: return r
u = (param("u") or "").strip()
if not u or len(u) > 60 or any(c in "<>\"'" for c in u): return jsonify({"ok": False, "error": "u required (max 60 chars, no html)"}), 400
return jsonify(user_probe(u))
# ---------- 2d. DOMAIN RECON (RDAP + DNS + subdomains) ----------
def domain_report(d):
d = d.strip().lower().replace("https://", "").replace("http://", "").split("/")[0]
out = {"ok": True, "domain": d}
st, b = http("https://rdap.org/" + urllib.parse.quote(d), timeout=15)
rd = jf(b)
if rd:
out["rdap"] = {k: rd.get(k) for k in ("handle", "ldhName", "status", "events", "entities", "nameservers") if rd.get(k)}
evs = {}
for e in rd.get("events") or []:
evs[e.get("eventAction", "?")] = e.get("eventDate")
out["events"] = evs
ents = []
for e in rd.get("entities") or []:
roles = e.get("roles") or []
fn = ""
try:
v = e.get("vcardArray") or []
for item in (v[1] if len(v) > 1 else []):
if item and item[0] == "fn": fn = item[3]
except Exception: pass
if "registrar" in roles or "registrant" in roles: ents.append({"roles": roles, "name": fn})
out["entities"] = ents
else:
out["rdap_error"] = f"rdap.org returned {st}"
doh = "https://dns.google/resolve?name=" + urllib.parse.quote(d) + "&type="
recs = {}
for rt in ("A", "AAAA", "MX", "NS", "TXT", "CNAME"):
st, b = http(doh + rt, timeout=10)
j = jf(b)
if j and j.get("Answer"):
recs[rt] = [a.get("data") for a in j["Answer"]]
out["dns"] = recs
st, b = http("https://crt.sh/?q=%25." + urllib.parse.quote(d) + "&output=json", timeout=25)
subs = set()
j = jf(b)
if isinstance(j, list):
for row in j:
for nm in str(row.get("name_value", "")).split("\n"):
nm = nm.strip().lower().lstrip("*.")
if nm.endswith("." + d) and nm != d: subs.add(nm)
out["subdomains"] = sorted(subs)[:100]
out["subdomain_count"] = len(subs)
return out
@app.route("/domain", methods=["GET", "POST"])
def domain_tool():
res = ""
if request.method == "POST":
d = (param("d") or "").strip()
if d and len(d) <= 100:
try:
rep = domain_report(d)
evs = rep.get("events") or {}
ent = "; ".join(f'{"/".join(e["roles"])}: {e["name"]}' for e in (rep.get("entities") or [])) or "—"
ns = ", ".join(str(x.get("ldhName") or x) for x in (rep.get("nameservers") or rep.get("rdap", {}).get("nameservers") or [])) or (rep.get("dns", {}).get("NS") and ", ".join(rep["dns"]["NS"])) or "—"
dns_rows = "".join(f"
{esc(k)}
{esc(' '.join(v))}
" for k, v in (rep.get("dns") or {}).items())
subs = rep.get("subdomains") or []
res = kv([("Registrar info", esc(ent)), ("Registered", esc(evs.get("registration", "—"))), ("Expires", esc(evs.get("expiration", "—"))), ("Last changed", esc(evs.get("last changed", "—"))), ("Status", esc(", ".join(rep.get("rdap", {}).get("status") or []) or "—")), ("Nameservers", esc(ns))])
res += f'
Full passive recon on any domain: RDAP registration data (registrar, dates, status), live DNS records, and certificate-transparency subdomain discovery. Free, no keys.
{res}
API: GET /api/domain?d=example.com → JSON: rdap, events, entities, dns, subdomains.
""" + how(["Type the bare domain — no scheme, no path.",
"RDAP answers who runs it, when it was registered and when it expires.",
"DNS shows A/AAAA/MX/NS/TXT/CNAME — where it lives and what mail it accepts.",
"Certificate logs expose hostnames even when DNS tries to hide them — great for finding staging/hidden subdomains.",
"All sources are public registries — passive, no packets touch the target."])
body += gloss([("RDAP","modern successor to WHOIS — structured registration data"),("CT log","certificate-transparency log: every TLS cert ever issued, public"),("TXT","DNS records used for SPF/verification claims")])
body += agent_card('GET /api/domain?d=example.com', 'curl "https://dark0rbits.thetempleofdoom.com/api/domain?d=example.com"', 'RDAP registration, DNS records, CT-log subdomains. Passive OSINT, free.')
return page("domain", body)
@app.route("/api/domain", methods=["GET", "POST"])
def api_domain():
r = rate_limit("domain", 10, 60)
if r: return r
d = (param("d") or "").strip()
if not d or len(d) > 100: return jsonify({"ok": False, "error": "d required"}), 400
return jsonify(domain_report(d))
@app.route("/card", methods=["GET", "POST"])
def card():
result = ""
num = re.sub(r"\D", "", param("num") or "")[:19]
if num:
ok = luhn_ok(num)
tags = ['LUHN VALID' if ok else 'LUHN INVALID — fake/dead number']
brand = brand_of(num)
bl = bin_lookup(num[:8])
bank = (bl.get("bank") or {}).get("name", "—")
country = (bl.get("country") or {}).get("name", "—")
ctype = bl.get("type", "—")
prepaid = bl.get("prepaid", "—")
flags = []
if ctype == "prepaid" or prepaid is True: flags.append("PREPAID — commonly flagged by merchants")
rng = {"Visa":(13,16,19),"Mastercard":(16,),"Amex":(15,)}.get(brand,(13,15,16,19))
tags.append(f'length {len(num)} valid for {brand}' if len(num) in rng else f'LENGTH {len(num)} WRONG for {brand}')
result = f"""
{kv([("Brand",brand),("BIN",num[:8]),("Bank / Issuer",esc(bank)),("Country",esc(country)),("Type",str(ctype)),("Prepaid",str(prepaid))])}
Nothing stored. No charge, no auth — BIN + math validation only. Fraud "flagged" status lives at the issuer.
""" + how(["Paste the card number — it never leaves the request, nothing is stored.","Luhn checksum validates the digit structure instantly.","BIN (first 8 digits) reveals the issuer bank, brand, card type and country.","Prepaid BINs get flagged — merchants commonly reject them.","This CANNOT show balance or fraud-hold status; only the issuer knows that."])
body = f"""
{result}"""
body += gloss([("BIN","first 6-8 digits of a card — identifies issuer, country, brand"),("Luhn","checksum test every real card number passes"),("prepaid","issued as prepaid — elevated fraud risk")])
body += agent_card('POST /api/card num=4539148803436467', 'curl -X POST https://dark0rbits.thetempleofdoom.com/api/card -d num=4539148803436467', 'Luhn + BIN intel. 2c/metered with API key, free with PASS.')
return page("card", body)
@app.route("/api/card", methods=["POST"])
def api_card():
r = rate_limit("card", 30, 60)
if r: return r
num = re.sub(r"\D", "", param("num") or "")[:19]
if not num: return jsonify({"ok": False, "error": "num required"})
ok = luhn_ok(num)
bl = bin_lookup(num[:8])
return jsonify({"ok": True, "luhn": ok, "brand": brand_of(num), "length_ok": len(num) in
{"Visa":(13,16,19),"Mastercard":(16,),"Amex":(15,)}.get(brand_of(num),(13,15,16,19)),
"bin": {"issuer": (bl.get("bank") or {}).get("name"), "country": (bl.get("country") or {}).get("name"),
"type": bl.get("type"), "prepaid": bl.get("prepaid")},
"flags": (["prepaid-risk"] if (bl.get("type")=="prepaid" or bl.get("prepaid") is True) else []) + (["luhn-invalid"] if not ok else [])})
# ---------- 7i. SCREENSHOT SERVICE (chromium if present, else rendered-text fallback) ----------
def shot_url_ok(u):
if not re.match(r"^https?://", u): return None, "url must start with http:// or https://"
try:
host = urllib.parse.urlsplit(u).hostname or ""
except Exception:
return None, "url parse error"
if not host: return None, "url has no host"
try:
candidate = ipaddress.ip_address(host)
except ValueError:
candidate = None
if candidate:
if candidate.is_private or candidate.is_loopback or candidate.is_link_local or candidate.is_reserved: return None, "private/reserved IPs blocked"
return u, None
try:
resolved = ipaddress.ip_address(socket.gethostbyname(host))
except Exception:
return u, None # cannot resolve here — let the fetcher report the failure
if resolved.is_private or resolved.is_loopback or resolved.is_link_local or resolved.is_reserved: return None, "private/reserved IPs blocked"
return u, None
def shot_find_browser():
for b in ("chromium", "chromium-browser", "google-chrome", "google-chrome-stable"):
if shutil.which(b): return b
return None
def _shot_html_harvest(url):
"""HTTP fetch + readability-ish text harvest + page intel. No browser, no fake PNG."""
status, html_text = http(url, timeout=15)
out = {"http_status": status}
try:
title = re.search(r"]*>(.*?)", html_text, re.I | re.S)
if title: out["title"] = html.unescape(title.group(1)).strip()[:300]
desc = re.search(r']+name=["\']description["\'][^>]+content=["\'](.*?)["\']', html_text, re.I | re.S)
if desc: out["description"] = html.unescape(desc.group(1)).strip()[:400]
except Exception:
pass
intel = []
for m in re.finditer(r"]*>(.*?)", html_text, re.I | re.S):
t = html.unescape(re.sub(r"<[^>]+>", "", m.group(2))).strip()
if t: intel.append("h" + m.group(1) + ": " + t[:120])
if len(intel) >= 15: break
t = re.sub(r"(?is)<(script|style|noscript|svg)[^>]*>.*?\1>", " ", html_text)
t = re.sub(r"(?s)", " ", t)
t = re.sub(r"(?i)<(br|/p|/div|/li|/h[1-6]|/tr)[^>]*>", "\n", t)
t = re.sub(r"<[^>]+>", " ", t)
t = html.unescape(t)
t = re.sub(r"[ \t\r]+", " ", t)
t = re.sub(r"\n\s*\n+", "\n", t).strip()
words = t.split()
out["text_preview"] = " ".join(words[:400])
out["text_chars_total"] = len(words)
out["headings"] = intel
return out
def shot_run(sid):
con = db()
s = con.execute("SELECT * FROM shots WHERE id=?", (sid,)).fetchone()
if not s: return
url = s["url"]
browser = shot_find_browser()
if browser:
out = os.path.join(UPLOAD_DIR, f"shot_{sid}.png")
try:
cmd = [browser, "--headless=new", "--no-sandbox", "--disable-gpu", "--hide-scrollbars",
"--window-size=1280,1600", f"--screenshot={out}", "--virtual-time-budget=8000", url]
p = subprocess.run(cmd, capture_output=True, timeout=45)
if p.returncode == 0 and os.path.exists(out) and os.path.getsize(out) > 0:
with open(out, "rb") as f: png = f.read()
os.remove(out)
con.execute("UPDATE shots SET status=?, result=? WHERE id=?", ("done", base64.b64encode(png).decode(), sid))
con.commit(); return
err = (p.stderr or b"").decode(errors="replace")[:200]
result = {"error": "chromium render failed: " + (err or f"exit {p.returncode}")}
except subprocess.TimeoutExpired:
result = {"error": "chromium timed out after 45s"}
except Exception as e:
result = {"error": f"chromium error: {e}"}
else:
try:
result = _shot_html_harvest(url)
result["mode"] = "text_fallback"
except Exception as e:
result = {"error": f"fetch failed: {e}"}
con.execute("UPDATE shots SET status=?, result=? WHERE id=?", ("text_fallback" if "mode" in result else "error", json.dumps(result), sid))
con.commit()
SHOT_API = ("
AGENT API
POST " + SITE + """/api/shot/create
Content-Type: application/json (or form fields)
{"url":"https://example.com"}
-> {"ok":true,"id":42,"status":"queued","poll":"BASE/api/shot/status/42"}
GET /api/shot/status/42
-> {"ok":true,"id":42,"status":"done","png_b64":"iVBORw..."} (chromium present)
-> {"ok":true,"status":"text_fallback","title":"...","text_preview":"...","headings":[...]}
auth: session cookie or Authorization: Bearer dk_...
25c/shot, free with PASS - rate limit 6/min
PNG mode: status "done" + png_b64. If chromium vanishes, expect text_fallback.
""").replace("BASE", SITE)
SHOT_EXPLAINER = """
HOW CAPTURE WORKS
• With headless Chromium installed, /shot returns a real browser render as base64 PNG.
• No browser on the host? You get text_fallback: an honest fetch of the page with rendered-text preview + page intel. A status field always tells you which.
• SSRF guard: private/reserved network targets are refused before any fetch.
• 25¢ per shot, free with PASS. Rate limit 6/min.
"""
@app.route("/shot")
def shot_page():
body = f"""
SCREEN SHOT
Point at a URL, get a real 1280×1600 headless-Chromium PNG render (base64 in the API). Honest text+intel fallback only if the renderer is down. Never a fake image.
New capture
{'Free with your PASS — or 25¢ from balance.' if current_user_id() else 'Login + balance (or PASS): 25¢ per shot.'}
Result
{SHOT_EXPLAINER}
""" + SHOT_API + how(["Paste a URL — the job queues instantly (free).",
"With a headless browser on the host you get a real PNG back as base64.",
"No browser installed? You get text_fallback: title, description, headings, first 400 words — honestly labeled.",
"Agents: POST /api/shot/create then poll /api/shot/status/ until status != queued.",
"SSRF guard: localhost and private ranges are refused — this is a capture service, not a port scanner."])
return page("shot", body)
@app.route("/api/shot/create", methods=["POST"])
def api_shot_create():
r = rate_limit("shot", 6, 60)
if r: return r
uid = key_user() or current_user_id()
if not uid: return jsonify({"ok": False, "error": "auth required: account session (sign up at /inbox, no KYC) or Authorization: Bearer dk_ key"}), 401
url = str(jp("url") or "").strip()
if not url: return jsonify({"ok": False, "error": "url required"}), 400
url, err = shot_url_ok(url)
if err: return jsonify({"ok": False, "error": err}), 400
if not has_pass(uid) and not charge(uid, 25, "shot create"):
return jsonify({"ok": False, "error": "insufficient balance", "balance_cents": get_balance(uid), "topup": SITE + "/keys"}), 402
con = db()
cur = con.execute("INSERT INTO shots(user_id,url,status,created) VALUES(?,?,?,?)", (uid, url, "queued", int(time.time())))
con.commit()
shot_run(cur.lastrowid)
st = con.execute("SELECT status FROM shots WHERE id=?", (cur.lastrowid,)).fetchone()
return jsonify({"ok": True, "id": cur.lastrowid, "status": st["status"], "poll": f"{SITE}/api/shot/status/{cur.lastrowid}"}), 200, {"Cache-Control": "no-store"}
def shot_dict(row):
d = {"ok": True, "id": row["id"], "status": row["status"]}
try:
r = json.loads(row["result"]) if row["result"] else None
except Exception:
r = row["result"]
if row["status"] == "done" and r:
d["png_b64"] = r
try:
d["png_bytes"] = len(base64.b64decode(r))
except Exception:
pass
elif r:
d.update(r if isinstance(r, dict) else {"detail": str(r)[:400]})
return d
@app.route("/api/shot/status/")
def api_shot_status(sid):
con = db()
s = con.execute("SELECT * FROM shots WHERE id=?", (sid,)).fetchone()
if not s: return jsonify({"ok": False, "error": "unknown shot id"}), 404
if s["status"] == "queued": shot_run(sid) # lazy exec (reload-safe)
s = con.execute("SELECT * FROM shots WHERE id=?", (sid,)).fetchone()
return jsonify(shot_dict(s))
# ---------- 3. SMS RENTALS ----------
SMSP = "https://api.smspool.net"
SERVICES = [("google","Google"),("discord","Discord"),("telegram","Telegram"),("whatsapp","WhatsApp"),("other","Other/Any")]
COUNTRIES = [("1","United States"),("2","United Kingdom"),("4","Netherlands"),("22","Russia"),("150","Germany")]
def sms_api(path, **kw):
if kw:
kw["key"] = SMSP_KEY
return http(f"{SMSP}/{path}", data=urllib.parse.urlencode(kw).encode(), method="POST")
return http(f"{SMSP}/{path}?key={SMSP_KEY}")
def sms_guard():
con = db(); now = int(time.time())
uid = current_user_id()
st, b = sms_api("request/balance")
bal = jf(b) or {}
try: bal = float(bal.get("balance", 0))
except Exception: bal = 0
if bal < 5: return f"house balance too low (${bal:.2f}) — rentals paused"
act = con.execute("SELECT COUNT(*) c FROM sms_rentals WHERE status='active' AND expires > ?", (now,)).fetchone()["c"]
if act >= (5 if has_pass(uid) else 3): return "too many active rentals right now — try again later"
h = con.execute("SELECT COUNT(*) c FROM sms_rentals WHERE created > ?", (now-3600,)).fetchone()["c"]
if h >= (20 if has_pass(uid) else 6): return "hourly rental cap reached"
d = con.execute("SELECT COUNT(*) c FROM sms_rentals WHERE created > ?", (now-86400,)).fetchone()["c"]
if d >= (50 if has_pass(uid) else 15): return "daily rental cap reached"
return None
@app.route("/sms", methods=["GET", "POST"])
def sms():
uid = current_user_id()
msg = ""
if request.method == "POST":
act = request.form.get("act")
if act == "rent":
guard = sms_guard()
if guard:
msg = f'
PAUSED {guard}
'
else:
st, b = sms_api("purchase/sms", service=request.form["service"], country=request.form["country"])
d = jf(b) or {}
if d.get("success") == 1:
con = db(); now = int(time.time())
con.execute("INSERT INTO sms_rentals(user_id,phone,service,country,purchase_id,cost,status,created,expires) VALUES(?,?,?,?,?,?,?,?,?)",
(uid, d.get("number"), request.form["service"], request.form["country"], str(d.get("purchase_id")), d.get("cost",0), "active", now, now+1800))
con.commit()
msg = f'
RENTED Your number: +{d.get("number")} · 30 min · order #{d.get("purchase_id")}
'
else:
msg = f'
RENT FAILED
{esc(b[:400])}
'
elif act == "check":
st, b = sms_api("sms/check", orderid=request.form["pid"])
d = jf(b) or {}
sms_txt = d.get("sms") or d.get("code") or ""
status = d.get("status", "?")
msg = f'
STATUS: {status} {"" + esc(sms_txt) + "" if sms_txt else "no code yet — poll again in 10s"}
'
elif act == "cancel":
st, b = sms_api("sms/cancel", orderid=request.form["pid"])
d = jf(b) or {}
ok = d.get("success") == 1
con = db(); con.execute("UPDATE sms_rentals SET status=? WHERE purchase_id=?", ("refunded" if ok else "cancel-failed", request.form["pid"])); con.commit()
msg = f'
{"CANCELLED + REFUNDED" if ok else "CANCEL FAILED"}
'
con = db()
hist = con.execute("SELECT * FROM sms_rentals WHERE user_id=? ORDER BY id DESC LIMIT 8", (uid,)).fetchall()
hist_rows = "".join(f"
Disposable numbers, 30-minute windows, free — the lab picks up the tab. Cancel before a code = instant burn.
Rent a number
Check / manage
{msg}
Recent rentals
Number
Service
Status
Order
Window
{hist_rows or '
none yet
'}
Live code
API: POST /api/sms/rent (service,country) · GET /api/sms/check?pid= · GET /api/sms/cancel?pid= · GET /api/sms/history
""" + how(["Pick a service and country, rent — the number is live for 30 minutes exactly.","Use it for any signup/verification. The code arrives as a text.","Poll the order (auto or manual) until the code shows.","Cancel before a code arrives and you get every satoshi back.","Each rental is logged in the recent-rentals table with a live countdown."])
body += gloss([("OTC","one-time code — the PIN a service texts you"),("burn","cancel an unused rental inside the refund window"),("SMSPool","our upstream number provider")])
return page("sms", body)
@app.route("/api/sms/rent", methods=["POST"])
def api_sms_rent():
guard = sms_guard()
if guard: return jsonify({"success": 0, "message": guard, "paused": True})
uid = key_user() or current_user_id()
if uid and not has_pass(uid) and get_balance(uid) < 50:
return jsonify({"ok": False, "error": "insufficient balance", "topup": SITE + "/keys"}), 402
st, b = sms_api("purchase/sms", service=param("service"), country=param("country"))
d = jf(b) or {}
if d.get("success") == 1:
con = db(); now = int(time.time())
con.execute("INSERT INTO sms_rentals(user_id,phone,service,country,purchase_id,cost,status,created,expires) VALUES(?,?,?,?,?,?,?,?,?)",
(uid, d.get("number"), param("service"), param("country"), str(d.get("purchase_id")), d.get("cost",0), "active", now, now+1800))
con.commit()
cost = int(d.get("cost_in_cents") or 5)
if uid and not has_pass(uid):
charge(uid, cost, f"sms rental +{d.get('number')}")
return jsonify(d)
@app.route("/api/sms/check", methods=["GET","POST"])
def api_sms_check():
st, b = sms_api("sms/check", orderid=param("pid"))
return jf(b) or jsonify({"error": b[:200]})
@app.route("/api/sms/cancel", methods=["GET","POST"])
def api_sms_cancel():
st, b = sms_api("sms/cancel", orderid=param("pid"))
d = jf(b) or {}
if d.get("success") == 1:
con = db(); con.execute("UPDATE sms_rentals SET status='refunded' WHERE purchase_id=?", (param("pid"),)); con.commit()
return d
@app.route("/api/sms/history")
def api_sms_history():
con = db(); now = int(time.time())
con.execute("UPDATE sms_rentals SET status='expired' WHERE status='active' AND expires < ?", (now,))
con.commit()
uid = key_user() or current_user_id()
if not uid:
return jsonify({"ok": False, "error": "login required (POST /inbox act=login)"}), 401
return jsonify([dict(r) for r in con.execute("SELECT * FROM sms_rentals WHERE user_id=? ORDER BY id DESC LIMIT 50", (uid,))])
# ---------- 4. PROXY LAB ----------
@app.route("/proxy", methods=["GET", "POST"])
def proxy():
result = ""
if request.method == "POST" and request.form.get("act") == "test":
user, pw = request.form.get("user",""), request.form.get("pass","")
pauth = base64.b64encode(f"{user}:{pw}".encode()).decode()
try:
s = socket.create_connection((PLEIADES_GW.split(":")[0], int(PLEIADES_GW.split(":")[1])), timeout=15)
s.sendall(f"CONNECT ip-api.com:80 HTTP/1.1\r\nHost: ip-api.com:80\r\nProxy-Authorization: Basic {pauth}\r\n\r\n".encode())
resp = s.recv(4096)
if b"200" in resp.split(b"\r\n")[0]:
s.sendall(b"GET /json/?fields=66846719 HTTP/1.1\r\nHost: ip-api.com\r\nConnection: close\r\n\r\n")
data = b""
while True:
c = s.recv(8192)
if not c: break
data += c
s.close()
j = jf(data.split(b"\r\n\r\n",1)[-1].decode("utf-8","replace")) or {}
con = db()
con.execute("INSERT INTO proxy_checks(user_key,egress_ip,geo,ok,ts) VALUES(?,?,?,?,?)", (user[:12], j.get("query","?"), f"{j.get('country')}/{j.get('city')}", 1, int(time.time())))
con.commit()
result = f'
'
else:
con = db()
con.execute("INSERT INTO proxy_checks(user_key,egress_ip,geo,ok,ts) VALUES(?,?,?,?,?)", (user[:12], "", "", 0, int(time.time())))
con.commit()
result = f'
AUTH/TUNNEL FAILED
{esc(resp[:200])}
'
except Exception as e:
result = f'
ERROR {esc(e)}
'
body = f"""
PROXY LAB
Test + rent residential proxies on the Pleiades rail — same gateway keys as everywhere.
API: POST /api/proxy/test (user, pass) → egress IP + geo JSON.
""" + how(["Enter your Pleiades gateway user:pass — the same credentials work across the fleet.","The lab tunnels a CONNECT request through the gateway and reports the true egress IP, geo and ISP.","Use the geo builder to steer the exit: region, country, city, sticky 30-min sessions.","Need bandwidth? Buy GB plans at the Pleiades storefront."])
body += gloss([("sticky session","same exit IP kept across requests"),("egress","the exit IP the rest of the internet sees"),("Pleiades","our proxy gateway network")])
return page("proxy", body)
@app.route("/api/proxy/test", methods=["POST"])
def api_proxy_test():
r = rate_limit("proxytest", 10, 60)
if r: return r
user, pw = param("user") or "", param("pass") or ""
pauth = base64.b64encode(f"{user}:{pw}".encode()).decode()
try:
s = socket.create_connection((PLEIADES_GW.split(":")[0], int(PLEIADES_GW.split(":")[1])), timeout=15)
s.sendall(f"CONNECT ip-api.com:80 HTTP/1.1\r\nHost: ip-api.com:80\r\nProxy-Authorization: Basic {pauth}\r\n\r\n".encode())
resp = s.recv(4096)
if b"200" not in resp.split(b"\r\n")[0]: return jsonify({"ok": False, "raw": resp[:120].decode("utf-8","replace")})
s.sendall(b"GET /json/?fields=66846719 HTTP/1.1\r\nHost: ip-api.com\r\nConnection: close\r\n\r\n")
data = b""
while True:
c = s.recv(8192)
if not c: break
data += c
s.close()
j = jf(data.split(b"\r\n\r\n",1)[-1].decode("utf-8","replace")) or {}
return jsonify({"ok": True, "egress": j})
except Exception as e:
return jsonify({"ok": False, "error": str(e)})
# ---------- 5. STEGO LAB ----------
def _keystream(password, n):
ks = b""; seed = password.encode()
while len(ks) < n:
seed = hashlib.sha256(seed).digest()
ks += seed
return ks[:n]
def steg_hide(img_bytes, text, password="", bits=1, spread="sequential"):
from PIL import Image
im = Image.open(io.BytesIO(img_bytes)).convert("RGBA")
px = im.load()
w, h = im.size
capacity = w * h * 3 * bits
payload = text.encode("utf-8")
phash = hashlib.sha256(password.encode()).digest()[:4] if password else b"\x00\x00\x00\x00"
header = b"AUR1" + struct.pack(">I", len(payload)) + phash
body = payload
if password:
body = bytes(a ^ b for a, b in zip(body, _keystream(password, len(body))))
data = header + body
if len(data) * 8 > capacity:
return None, f"too big: need {len(data)*8} bits, image holds {capacity}"
if spread == "random":
import random as _r
_r.seed(int.from_bytes(hashlib.sha256((password + "dark0rbits").encode()).digest()[:4], "big") if password else int.from_bytes(hashlib.sha256(b"dark0rbits-random-no-pass").digest()[:4], "big"))
order = list(range(w*h)); _r.shuffle(order)
else:
order = list(range(w*h))
bits_needed = len(data) * 8
idx = 0
mask = (1 << bits) - 1
for pos in order:
if idx >= bits_needed: break
x, y = pos % w, pos // w
r, g, b, a = px[x, y]
chs = [r, g, b]
for ch_i in range(3):
if idx >= bits_needed: break
chunk = 0
taken = 0
for k in range(bits):
if idx >= bits_needed: break
chunk = (chunk << 1) | ((data[idx >> 3] >> (7 - (idx & 7))) & 1)
idx += 1; taken += 1
if taken < bits: chunk <<= (bits - taken)
chs[ch_i] = (chs[ch_i] & ~mask) | chunk
px[x, y] = tuple(chs) + (a,)
# also stash settings in a tEXt chunk for reliable extraction hints
out = io.BytesIO()
im.save(out, "PNG", pnginfo=_pnginfo(bits, spread))
return out.getvalue(), {"bits": bits, "spread": spread}
def _pnginfo(bits, spread):
try:
from PIL.PngImagePlugin import PngInfo
info = PngInfo()
info.add_text("dark0rbits_meta", json.dumps({"bits": bits, "spread": spread, "v": 2}))
return info
except Exception:
return None
def steg_extract(img_bytes, password="", bits=None, spread=None):
from PIL import Image
im = Image.open(io.BytesIO(img_bytes))
meta = im.info.get("dark0rbits_meta") or im.info.get("auriga_meta")
if meta:
try:
m = json.loads(meta)
bits = int(m.get("bits", bits or 1)); spread = m.get("spread", spread or "sequential")
except Exception: pass
bits = bits or 1
im = im.convert("RGBA")
px = im.load()
w, h = im.size
mask = (1 << bits) - 1
# replicate the shuffle used at hide time
if spread == "random":
import random as _r
_r.seed(int.from_bytes(hashlib.sha256((password + "dark0rbits").encode()).digest()[:4], "big") if password else int.from_bytes(hashlib.sha256(b"dark0rbits-random-no-pass").digest()[:4], "big"))
order = list(range(w*h)); _r.shuffle(order)
else:
order = list(range(w*h))
raw = bytearray()
need = None
idx = 0
for pos in order:
if need is not None and idx >= need: break
x, y = pos % w, pos // w
r, g, b, a = px[x, y]
for ch in (r, g, b):
chunk = ch & mask
for k in range(bits-1, -1, -1):
if need is not None and idx >= need: break
bit = (chunk >> k) & 1
while len(raw) < (idx >> 3) + 1: raw.append(0)
if bit: raw[idx >> 3] |= (0x80 >> (idx & 7))
idx += 1
if need is not None and idx >= need: break
if need is None and idx >= 64:
if bytes(raw[:4]) != b"AUR1":
return None, f"no DARK0RBITS payload found with LSB depth {bits} (try other depth / randomized)"
ln = struct.unpack(">I", bytes(raw[4:8]))[0]
need = 96 + ln * 8 # header is 12 bytes (AUR1+len+phash) = 96 bits; old 64 truncated 4 bytes off every payload
data = bytes(raw)
if len(data) < 12: return None, "payload too small"
if bytes(data[:4]) != b"AUR1":
return None, "no DARK0RBITS payload found (wrong password or settings?)"
if password and hashlib.sha256(password.encode()).digest()[:4] != data[8:12]:
return None, "wrong password"
ln = struct.unpack(">I", data[4:8])[0]
body = data[12:12+ln]
if password:
body = bytes(a ^ b for a, b in zip(body, _keystream(password, len(body))))
text = body.decode("utf-8", "replace")
return text, None
@app.route("/steg", methods=["GET"])
def steg():
body = f"""
STEGO LAB
Hide secret text inside an ordinary PNG so completely that the picture looks untouched — no metadata, no visible change, nothing to see. Only someone who knows it's there (and has the password) can read it back.
Hide text in a picture
The download is a normal PNG. Post it, email it, host it — the secret rides along.
Read hidden text back
API: POST /api/steg/hide (image, text, password?, bits 1-3, spread) → PNG · POST /api/steg/extract (image, password?, bits?, spread?) → JSON
""" + flow("smuggle a passphrase through a photo wall", [
"you drop in a vacation photo — the meter says 1920×1080 holds ~777,600 hidden characters. Plenty.",
"you type the wifi password hunter2-sunset-2026, add password peanut, spread randomized, hit Hide.",
"the site flips the least-significant bits of random pixels — the downloaded PNG looks pixel-for-pixel identical to the original.",
"you post the photo publicly. It passes through phones, compressors, screenshots — it's just a picture.",
"ally saves it, opens STEGO LAB, drops the file, types peanut → the words come back.",
"stranger drops the same file with no password → noise. Without the key, it's a photo of a beach."]) + how([
"Every pixel's color is three numbers. Change the last binary digit of each — changes of ±1 in brightness — and no eye can tell.",
"Depth 1 hides ~1 character per 2–3 pixels: invisible and robust. Depth 2–3 packs more but survives re-compression worse.",
"Randomized spread scatters your bits across the whole image instead of the top rows — a cropped picture can still give the text back.",
"A password encrypts the payload AND seeds the scatter pattern: wrong password yields pure noise, not garbage text.",
"Extraction auto-reads the embedded settings — the file knows its own depth and spread. Just drop and go.",
"Warning: posting to platforms that re-compress (Instagram, WhatsApp) can damage depth-1 edges — send the file itself, unmodified."])
body += gloss([("LSB","least significant bit — the final binary digit of a color value; changing it is invisible"),("depth","how many bit-planes carry the payload — more depth, more text, more detectable"),("spread","where the bits live: top-down or scattered across the image"),("carrier","the innocent-looking picture that transports your hidden text")])
body += agent_card('POST /api/steg/hide image= text=hi [password= bits= spread=]', 'curl -X POST https://dark0rbits.thetempleofdoom.com/api/steg/hide -F image=@beach.png -F text="wifi is hunter2" -F password=peanut', 'Extract: POST /api/steg/extract (image, password?). Free, 20/min.')
return page("steg", body)
@app.route("/api/steg/hide", methods=["POST"])
def api_steg_hide():
r = rate_limit("steg", 20, 60)
if r: return r
f = request.files.get("image")
text = param("text") or ""
if not f or not text: return jsonify({"ok": False, "error": "image + text required"}), 400
bits = min(3, max(1, int(param("bits") or 1)))
spread = param("spread") or "sequential"
try:
out, meta = steg_hide(f.read(), text, param("password") or "", bits, spread)
except Exception as e:
return jsonify({"ok": False, "error": str(e)}), 400
if out is None: return jsonify({"ok": False, "error": meta}), 400
return send_file(io.BytesIO(out), mimetype="image/png", as_attachment=True, download_name="dark0rbits-hidden.png")
@app.route("/api/steg/extract", methods=["POST"])
def api_steg_extract():
r = rate_limit("steg", 20, 60)
if r: return r
f = request.files.get("image")
if not f: return jsonify({"ok": False, "error": "image required"}), 400
bits = param("bits")
bits = min(3, max(1, int(bits))) if bits else None
try:
text, err = steg_extract(f.read(), param("password") or "", bits, param("spread") or None)
except Exception as e:
return jsonify({"ok": False, "error": str(e)}), 400
if err: return jsonify({"ok": False, "error": err}), 200
return jsonify({"ok": True, "text": text})
# ---------- 6. TRACKABLE FILES ----------
@app.route("/track", methods=["GET"])
def track():
uid = current_user_id()
mine = ""
if uid:
con = db()
rows = con.execute("SELECT * FROM trackables WHERE user_id=? ORDER BY id DESC LIMIT 15", (uid,)).fetchall()
if rows:
trs = "".join(
f"
Upload any file or picture and get a tracked link for it. The moment anyone opens that link — or views the email version — their IP, city, ISP, device and language fire back into your INBOX. The image-IP trick, weaponized and clean.
1 · Name your bait
{mine}
How it works: your file gets a secret link — every open is logged (time, IP, device) and lands in your inbox with geo. You also get an HTML copy with an embedded tracking pixel: email THAT and every view fires too. Login (no KYC) to see events.
API: POST /api/track/create (filename) → upload_url · POST /api/track/upload?token= (file) → tracked_link + pixel + email_html · GET /api/track/events?token=
""" + flow("learn who opens your 'photo'", [
"you create a trackable named sunset.jpg — free, instant, and the upload page opens.",
"you upload the actual photo. You get back: a tracked link, a pixel URL, and an email-ready HTML copy.",
"you send the link — 'hey check out this pic'. That's the whole trick.",
"them taps it. The image renders normally in their browser — but the page quietly pings home first.",
"you INBOX lights up: sunset.jpg opened — IP 203.0.113.7 · Rotterdam NL · KPN · Android Chrome · timezone Europe/Amsterdam.",
"the HTML copy works over email too — every preview pane that loads images fires the pixel, no click needed."]) + how([
"Free now — click create and the upload opens instantly, no payment.",
"Upload your file or picture: you get a secret tracked link plus an email-ready HTML copy.",
"Email the HTML copy or share the link — every open fires back.",
"Each open reports: exact time, real IP, city/country, ISP, timezone, VPN flag, device, language, referrer.",
"Alerts land in your INBOX the second it happens; full event log via the API."])
return page("track", body)
BTCPAY_PUBLIC = "https://btcpay.thetempleofdoom.com"
def public_checkout(link):
"""LAN invoices must be payable from the open internet — swap host on checkout links."""
if not link:
return link
return link.replace("https://10.30.20.140", BTCPAY_PUBLIC)
def btc_invoice(amount="1.00"):
st, b = http(f"{BTCPAY}/stores/{BTCPAY_STORE}/invoices",
headers={"Authorization": "token " + BTCPAY_KEY, "Content-Type": "application/json"},
data=json.dumps({"amount": amount, "currency": "USD", "metadata": {"orderId": "dark0rbits-track"}}).encode(), method="POST")
return jf(b) or {}
@app.route("/api/track/create", methods=["POST"])
def api_track_create():
fn = param("filename") or "file"
uid = key_user() or current_user_id()
if not uid:
return jsonify({"ok": False, "error": "login required — create a no-KYC account at /inbox (POST /inbox act=register), then retry"}), 401
token = secrets.token_urlsafe(16)
con = db()
if has_pass(uid):
con.execute("INSERT INTO trackables(user_id,token,filename,kind,invoice_id,paid,created) VALUES(?,?,?,?,?,1,?)",
(uid or 0, token, esc(fn[:100]), "file", "PASS", int(time.time())))
con.commit()
return jsonify({"ok": True, "free": True, "token": token, "upload_url": f"{SITE}/track/pay?token={token}"})
if uid and charge(uid, 100, f"trackable file ({fn[:40]})"):
con.execute("INSERT INTO trackables(user_id,token,filename,kind,invoice_id,paid,created) VALUES(?,?,?,?,?,1,?)",
(uid or 0, token, esc(fn[:100]), "file", "BALANCE", int(time.time())))
con.commit()
return jsonify({"ok": True, "balance_charged": 1.00, "token": token, "upload_url": f"{SITE}/track/pay?token={token}"})
inv = btc_invoice()
if not inv.get("id"): return jsonify({"ok": False, "error": str(inv)[:200]}), 400
con.execute("INSERT INTO trackables(user_id,token,filename,kind,invoice_id,paid,created) VALUES(?,?,?,?,?,0,?)",
(uid or 0, token, esc(fn[:100]), "file", inv["id"], int(time.time())))
con.commit()
return _checkout_or_json({"ok": True, "invoice_id": inv["id"], "checkoutLink": public_checkout(inv.get("checkoutLink")), "token": token,
"after_payment_upload_url": f"{SITE}/track/pay?token={token}"})
@app.route("/track/pay", methods=["GET"])
def track_pay():
token = param("token") or ""
con = db()
t = con.execute("SELECT * FROM trackables WHERE token=?", (token,)).fetchone()
if not t: return page("track", "
TRACK FILE
unknown token
")
return page("track", f"""
TRACK FILE
Upload your file — then it's trackable.
""")
@app.route("/api/track/upload", methods=["POST"])
def api_track_upload():
token = param("token")
f = request.files.get("file")
if not f: return jsonify({"ok": False, "error": "file required"}), 400
con = db()
t = con.execute("SELECT * FROM trackables WHERE token=?", (token,)).fetchone()
if not t: return jsonify({"ok": False, "error": "unknown token"}), 400
st, b = http(f"{BTCPAY}/stores/{BTCPAY_STORE}/invoices/{t['invoice_id']}", headers={"Authorization": "token " + BTCPAY_KEY}) if t["invoice_id"] not in ("PASS", "BALANCE") else (200, '{"status":"settled"}')
inv = jf(b) or {}
paid = inv.get("status") in ("settled", "processing", "paid")
if not paid: return jsonify({"ok": False, "error": f"invoice not paid yet ({inv.get('status')})"}), 402
data = f.read()
open(os.path.join(UPLOAD_DIR, token + ".bin"), "wb").write(data)
kind = "image" if (f.content_type or "").startswith("image") else "file"
fn = (f.filename or t["filename"])[:100]
con.execute("UPDATE trackables SET paid=1, kind=?, filename=? WHERE token=?", (kind, fn, token))
con.commit()
b64 = base64.b64encode(data).decode()
pixel = f"{SITE}/t/{token}.png"
if kind == "image":
viewer = f''
else:
viewer = f'
'
open(os.path.join(UPLOAD_DIR, token + ".html"), "w").write(viewer)
con.execute("INSERT INTO track_events(trackable_id,ts,ip,ua) VALUES(?,?,?,?)", (t["id"], int(time.time()), "created", "upload"))
con.commit()
return jsonify({"ok": True, "tracked_link": f"{SITE}/t/{token}", "pixel": pixel,
"email_html": f"{SITE}/t/{token}/html",
"note": "attach/email the HTML version — every view fires the pixel and lands in the inbox"})
def _geo_cache():
con = db()
con.execute("CREATE TABLE IF NOT EXISTS geo_cache(ip TEXT PRIMARY KEY, geo TEXT, ts INTEGER)")
return con
def enrich_ip(ip):
"""geo/ISP/ASN for an IP, cached 24h."""
if not ip or ip == "created" or ip.startswith(("10.30.20.", "127.", "172.17.")): return {}
con = _geo_cache()
r = con.execute("SELECT geo FROM geo_cache WHERE ip=? AND ts > ?", (ip, int(time.time())-86400)).fetchone()
if r: return json.loads(r["geo"])
st, b = http(f"http://ip-api.com/json/{ip}?fields=66846719")
d = jf(b) or {}
geo = {k: d.get(k) for k in ("country","countryCode","regionName","city","zip","lat","lon","timezone","isp","org","as","asname","mobile","proxy","hosting","reverse","query") if d.get(k) is not None}
con.execute("INSERT OR REPLACE INTO geo_cache(ip,geo,ts) VALUES(?,?,?)", (ip, json.dumps(geo), int(time.time())))
con.commit()
return geo
def _log_open(t, extra=""):
con = db()
ip = request.headers.get("X-Real-IP") or request.remote_addr or "?"
ua = request.headers.get("User-Agent","")
lang = request.headers.get("Accept-Language","")
ref = request.headers.get("Referer","")
geo = enrich_ip(ip)
where = ""
if geo: where = f" — {geo.get('city','')}, {geo.get('regionName','')} {geo.get('countryCode','')} · {geo.get('isp','')} · tz {geo.get('timezone','')}"
if geo.get("proxy"): where += " · VPN/proxy ⚠"
con.execute("INSERT INTO track_events(trackable_id,ts,ip,ua) VALUES(?,?,?,?)",
(t["id"], int(time.time()), ip + (" " + json.dumps(geo) if geo else ""), ua[:200] + (f" | lang={lang}" if lang else "") + (f" | ref={ref[:100]}" if ref else "")))
uid = t["user_id"]
if uid:
con.execute("INSERT INTO messages(user_id,sender,body,created) VALUES(?,?,?,?)",
(uid, "operator-bot", f"👁 '{esc(t['filename'])}' just opened{extra} — IP {esc(ip)}{esc(where)} device: {esc(ua[:100])}{' lang: ' + esc(lang) if lang else ''}{' from: ' + esc(ref[:120]) if ref else ''}", int(time.time())))
con.commit()
@app.route("/t/")
def tracked_download(token):
con = db()
t = con.execute("SELECT * FROM trackables WHERE token=?", (token,)).fetchone()
if not t or not t["paid"]: return "not found", 404
_log_open(t, " (link)")
path = os.path.join(UPLOAD_DIR, token + ".bin")
if not os.path.exists(path): return "file gone", 404
return send_file(path, as_attachment=True, download_name=t["filename"])
@app.route("/t/.png")
def tracked_pixel(token):
con = db()
t = con.execute("SELECT * FROM trackables WHERE token=?", (token,)).fetchone()
if t and t["paid"]:
_log_open(t, " (email/pixel)")
px = base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")
return Response(px, mimetype="image/gif", headers={"Cache-Control": "no-store"})
@app.route("/t//html")
def tracked_html(token):
con = db()
t = con.execute("SELECT * FROM trackables WHERE token=?", (token,)).fetchone()
if not t or not t["paid"]: return "not found", 404
p = os.path.join(UPLOAD_DIR, token + ".html")
return send_file(p, mimetype="text/html") if os.path.exists(p) else ("no html wrapper", 404)
@app.route("/api/track/events", methods=["GET"])
def api_track_events():
con = db(); token = param("token")
t = con.execute("SELECT * FROM trackables WHERE token=?", (token,)).fetchone()
if not t: return jsonify({"ok": False, "error": "unknown token"})
uid = current_user_id()
if not uid or uid != t["user_id"]: return jsonify({"ok": False, "error": "auth required (login on /inbox)"})
return jsonify([dict(r) for r in con.execute("SELECT * FROM track_events WHERE trackable_id=? ORDER BY id DESC LIMIT 100", (t["id"],))])
# ---------- 6b. BURNER MAIL (receive-only, BTC packages) ----------
MAIL_PACKS = [("7","7 days — $3",3,7),("30","30 days — $8",8,30),("90","90 days — $20",20,90)]
MAIL_DOMAIN = "thetempleofdoom.com"
MAIL_RESERVED = {"indianaholmes","admin","operator","drjones","root","noreply","support","pass","mail"}
MAIL_SECRET = "dark0rbits-mail-relay-2026"
@app.route("/mail", methods=["GET"])
def mail():
uid = current_user_id()
mine = ""
if uid:
con = db(); now = int(time.time())
con.execute("UPDATE mailboxes SET paid=2 WHERE paid=1 AND expires < ?", (now,)) # expired
rows = con.execute("SELECT * FROM mailboxes WHERE user_id=? ORDER BY id DESC LIMIT 10", (uid,)).fetchall()
if rows:
trs = "".join(f"
Receive-only disposable mailboxes @thetempleofdoom.com. Counting down in real time. Anything you sign up for — codes, confirmations, one-off handouts — lands right here, no other identity attached.
Pick a package (free)
{''.join(f'' for d,n,_,_ in MAIL_PACKS)}
Pick your mailbox and length — it activates instantly. Free now, no invoice.
{mine}
API: POST /api/mail/create (local, days) → activates instantly (free) · GET /api/mail/inbox?addr= (needs login) — inbound via Cloudflare Email Routing → worker relay.
""" + how(["Pick a name and a package — 7, 30 or 90 days, all free now.","Pay the invoice; the mailbox activates the second it settles.","The address is receive-only: verification codes, confirmations, one-off handouts.","The countdown runs in real time; when it hits zero the mailbox retires itself.","All mail shows on the site inbox — nothing touches any other identity."])
return page("mail", body)
@app.route("/api/mail/create", methods=["POST"])
def api_mail_create():
uid = current_user_id()
local = re.sub(r"[^a-z0-9._-]", "", (param("local") or "").lower())[:30]
days = param("days") or "7"
pack = next((p for p in MAIL_PACKS if p[0] == str(days)), None)
if not pack: return jsonify({"ok": False, "error": "bad package"}), 400
if not local: return jsonify({"ok": False, "error": "mailbox name required"}), 400
if local in MAIL_RESERVED: return jsonify({"ok": False, "error": "reserved name"}), 400
addr = f"{local}@{MAIL_DOMAIN}"
con = db()
if con.execute("SELECT 1 FROM mailboxes WHERE address=?", (addr,)).fetchone():
return jsonify({"ok": False, "error": "mailbox name taken"}), 400
uid = key_user() or current_user_id()
# metered: PASS = instant free; balance = instant paid; else BTC invoice
if uid and has_pass(uid):
con.execute("INSERT INTO mailboxes(user_id,address,invoice_id,paid,expires,created,plan_days) VALUES(?,?,?,?,?,?,?)",
(uid, addr, "PASS", 1, int(time.time())+86400*pack[3], int(time.time()), pack[3]))
con.commit()
return jsonify({"ok": True, "free": True, "address": addr, "expires_in_days": pack[3]})
if uid and charge(uid, pack[2]*100, f"burner mailbox {addr} ({pack[3]}d)"):
con.execute("INSERT INTO mailboxes(user_id,address,invoice_id,paid,expires,created,plan_days) VALUES(?,?,?,?,?,?,?)",
(uid, addr, "BALANCE", 1, int(time.time())+86400*pack[3], int(time.time()), pack[3]))
con.commit()
return jsonify({"ok": True, "balance_charged": pack[2], "address": addr, "expires_in_days": pack[3]})
inv = btc_invoice(f"{pack[2]:.2f}")
if not inv.get("id"): return jsonify({"ok": False, "error": str(inv)[:200]}), 400
con.execute("INSERT INTO mailboxes(user_id,address,invoice_id,paid,expires,created,plan_days) VALUES(?,?,?,?,?,?,?)",
(uid or 0, addr, inv["id"], 0, 0, int(time.time()), pack[3]))
con.commit()
return _checkout_or_json({"ok": True, "address": addr, "checkoutLink": public_checkout(inv.get("checkoutLink")), "invoice_id": inv["id"]})
@app.route("/api/mail/inbound", methods=["POST"])
def api_mail_inbound():
d = request.get_json(silent=True) or {}
if d.get("secret") != MAIL_SECRET: return jsonify({"ok": False}), 403
addr = (d.get("mailbox") or "").lower().split("@")[0]
con = db()
m = con.execute("SELECT * FROM mailboxes WHERE address LIKE ? AND paid=1", (addr + "@%",)).fetchone()
if not m: return jsonify({"ok": False, "error": "unknown/expired mailbox"}), 404
con.execute("INSERT INTO mails(mailbox_id,sender,subject,body,ts) VALUES(?,?,?,?,?)",
(m["id"], esc(d.get("from") or "?"), esc(d.get("subject") or ""), esc(d.get("body") or ""), int(time.time())))
con.execute("UPDATE mailboxes SET cnt=cnt+1 WHERE id=?", (m["id"],))
con.commit()
return jsonify({"ok": True})
@app.route("/mail/view")
def mail_view():
uid = current_user_id()
if not uid: return page("mail", '
')
addr = param("addr") or ""
con = db()
m = con.execute("SELECT * FROM mailboxes WHERE address=? AND user_id=?", (addr.lower(), uid)).fetchone()
if not m: return page("mail", "
not your mailbox
")
mails = con.execute("SELECT * FROM mails WHERE mailbox_id=? ORDER BY id DESC LIMIT 100", (m["id"],)).fetchall()
rows = "".join(f'
'
left = max(0, m["expires"] - int(time.time()))
return page("mail", f"""
{esc(m['address'])}
remaining — auto-refreshes every 15s.
{rows}
""")
@app.route("/api/mail/inbox")
def api_mail_inbox():
uid = current_user_id()
if not uid: return jsonify({"ok": False, "error": "login required (POST /inbox act=login)"})
con = db(); addr = (param("addr") or "").lower()
m = con.execute("SELECT * FROM mailboxes WHERE address=? AND user_id=?", (addr, uid)).fetchone()
if not m: return jsonify({"ok": False, "error": "unknown mailbox"})
return jsonify([dict(r) for r in con.execute("SELECT sender,subject,body,ts FROM mails WHERE mailbox_id=? ORDER BY id DESC LIMIT 100", (m["id"],))])
# ---------- 6c. PASS — all-tools subscription ----------
PASS_PACKS = [("30","1 month — $10 BTC",10,30),("90","3 months — $25 (save 17%)",25,90),("365","1 year — $80 (save 33%)",80,365)]
def has_pass(uid):
if not uid: return False
con = db()
u = con.execute("SELECT username FROM users WHERE id=?", (uid,)).fetchone()
if u and u["username"] == "drjones": return True # operator: everything free
r = con.execute("SELECT 1 FROM passes WHERE user_id=? AND expires > ? AND paid=1", (uid, int(time.time()))).fetchone()
return bool(r)
@app.route("/pass", methods=["GET"])
def pass_page():
uid = current_user_id()
mine = ""
if uid:
con = db()
r = con.execute("SELECT * FROM passes WHERE user_id=? AND paid=1 ORDER BY expires DESC LIMIT 1", (uid,)).fetchone()
if r and r["expires"] > int(time.time()):
left = r["expires"] - int(time.time())
mine = f'
PASS ACTIVE {left//86400} days {left%86400//3600}h left — all tools unlimited (proxy rentals still metered at the storefront), trackables free, burner mail discounts.
'
body = f"""
PASS — EVERYTHING FREE
The meters are gone: unlimited SMS rentals, free trackables, burner mail, screenshots — every tool costs nothing. No PASS needed anymore.
{''.join(f'' for d,n,_,_ in PASS_PACKS)}
Proxy rentals stay separate (they burn real upstream bandwidth — buy those at the storefront).
{mine}
API: POST /api/pass/create (days=30|90|365) → invoice. Pass activates on payment settle via webhook.
"""
return page("pass", body)
@app.route("/api/pass/create", methods=["POST"])
def api_pass_create():
uid = current_user_id()
if not uid: return jsonify({"ok": False, "error": "login first (POST /inbox act=login)"}), 401
days = param("days") or "30"
pack = next((p for p in PASS_PACKS if p[0] == str(days)), None)
if not pack: return jsonify({"ok": False, "error": "bad package"}), 400
inv = btc_invoice(f"{pack[2]:.2f}")
if not inv.get("id"): return jsonify({"ok": False, "error": str(inv)[:200]}), 400
con = db()
con.execute("INSERT INTO passes(user_id,invoice_id,paid,expires,plan_days) VALUES(?,?,0,0,?)", (uid, inv["id"], pack[3]))
con.commit()
return _checkout_or_json({"ok": True, "checkoutLink": public_checkout(inv.get("checkoutLink")), "invoice_id": inv["id"]})
@app.route("/api/btcpay/webhook", methods=["POST"])
def btcpay_webhook():
sig = request.headers.get("BTCPay-Sig", "")
body = request.get_data()
expect = "sha256=" + hmac.new(BTCPAY_WHSEC.encode(), body, hashlib.sha256).hexdigest()
if sig != expect: return jsonify({"ok": False, "error": "bad sig"}), 400
d = jf(body) or {}
iid = d.get("invoiceId") or ""
if d.get("type") == "InvoiceSettled" or (d.get("type") == "InvoicePaymentSettled"):
con = db()
if iid:
if con.execute("SELECT 1 FROM wh_processed WHERE invoice_id=?", (iid,)).fetchone():
return jsonify({"ok": True, "dup": True})
con.execute("INSERT OR IGNORE INTO wh_processed(invoice_id,ts) VALUES(?,?)", (iid, int(time.time())))
con.execute("UPDATE trackables SET paid=1 WHERE invoice_id=?", (iid,))
r = con.execute("SELECT plan_days FROM mailboxes WHERE invoice_id=?", (iid,)).fetchone()
if r:
con.execute("UPDATE mailboxes SET paid=1, expires=? WHERE invoice_id=?", (int(time.time()) + 86400*int(r["plan_days"] or 7), iid))
r = con.execute("SELECT plan_days FROM passes WHERE invoice_id=?", (iid,)).fetchone()
if r:
con.execute("UPDATE passes SET paid=1, expires=? WHERE invoice_id=?", (int(time.time()) + 86400*int(r["plan_days"] or 30), iid))
# balance top-ups
try:
meta = d.get("metadata") or {}
if not meta:
st, b = http(f"{BTCPAY}/stores/{BTCPAY_STORE}/invoices/{iid}", headers={"Authorization": "token " + BTCPAY_KEY})
meta = (jf(b) or {}).get("metadata", {}) or {}
if str(meta.get("orderId", "")).startswith("dark0rbits-topup"):
uid = int(meta["orderId"].split(":")[1]); cents = int(meta["orderId"].split(":")[2])
con.execute("INSERT OR IGNORE INTO balances(user_id, cents) VALUES(?, 0)", (uid,))
con.execute("UPDATE balances SET cents = cents + ? WHERE user_id=?", (cents, uid))
con.execute("INSERT INTO ledger(user_id,delta_cents,reason,ts) VALUES(?,?,?,?)", (uid, cents, f"BTC topup {iid}", int(time.time())))
except Exception: pass
con.commit()
return jsonify({"ok": True})
# ---------- 6h. API KEYS + BALANCE ----------
@app.route("/keys", methods=["GET", "POST"])
def keys():
uid = current_user_id()
if not uid:
return page("keys", '
API KEYS
login on /inbox first — keys are bound to your account.
')
con = db()
if request.method == "POST" and request.form.get("act") == "mkkey":
label = (param("label") or "default")[:40]
key = "dk_" + secrets.token_urlsafe(24)
con.execute("INSERT INTO apikeys(user_id,key,label,created) VALUES(?,?,?,?)", (uid, key, esc(label), int(time.time())))
con.commit()
newkey = key
else:
newkey = None
rows = con.execute("SELECT * FROM apikeys WHERE user_id=? AND revoked=0 ORDER BY id DESC", (uid,)).fetchall()
bal = get_balance(uid)
led = con.execute("SELECT * FROM ledger WHERE user_id=? ORDER BY id DESC LIMIT 15", (uid,)).fetchall()
led_html = "".join(f"
Metered access is over — every tool is free for humans and agents. No top-ups, no meters, no KYC. Your API keys still work everywhere.
New API key
{newkey_block}
{keys_block}
Top up (BTC)
{''.join(f'' for c,a in [(500,'$5'),(2000,'$20'),(10000,'$100')])}
Invoice settles → balance credited automatically via webhook.
Ledger
Δ
Reason
When
{led_html or '
no charges yet
'}
Use it: Authorization: Bearer dk_… header on any paid API call. Metered endpoints: /api/sms/rent (pass-through cost), /api/mail/create (package price), /api/track/create ($1). Everything else free. PASS = no metering.
"""
return page("keys", body)
@app.route("/api/balance/topup", methods=["POST"])
def api_balance_topup():
uid = current_user_id()
if not uid: return jsonify({"ok": False, "error": "login required — free no-KYC account at /inbox"}), 401
cents = int(param("cents") or 500)
if cents not in (500, 2000, 10000): return jsonify({"ok": False, "error": "bad amount"}), 400
# invoice created WITH topup metadata in one shot
st, b = http(f"{BTCPAY}/stores/{BTCPAY_STORE}/invoices",
headers={"Authorization": "token " + BTCPAY_KEY, "Content-Type": "application/json"},
data=json.dumps({"amount": f"{cents/100:.2f}", "currency": "USD",
"metadata": {"orderId": f"dark0rbits-topup:{uid}:{cents}", "itemDesc": "dark0rbits balance topup"}}).encode(), method="POST")
inv = jf(b) or {}
if not inv.get("id"): return jsonify({"ok": False, "error": str(inv)[:200]}), 400
con = db()
con.execute("INSERT INTO ledger(user_id,delta_cents,reason,ts) VALUES(?,?,?,?)", (uid, 0, f"topup invoice {inv['id']} pending", int(time.time())))
con.commit()
return _checkout_or_json({"ok": True, "checkoutLink": public_checkout(inv.get("checkoutLink"))})
@app.route("/api/balance")
def api_balance():
uid = key_user() or current_user_id()
if not uid: return jsonify({"ok": False, "error": "auth required"}), 401
return jsonify({"ok": True, "balance_cents": get_balance(uid), "pass_active": has_pass(uid)})
# ---------- 6d. EMAIL HEADER FORENSICS ----------
def parse_headers(raw):
import email as em
msg = em.message_from_string(raw)
out = {"from": msg.get("From",""), "to": msg.get("To",""), "subject": msg.get("Subject",""),
"date": msg.get("Date",""), "return_path": msg.get("Return-Path",""),
"reply_to": msg.get("Reply-To",""), "message_id": msg.get("Message-ID","")}
hops = []
for h in msg.get_all("Received", []) or []:
hop = h.strip().replace("\n", " ")
hops.append(hop[:400])
out["hops"] = list(reversed(hops)) # first-hop origin first
# timestamps per hop → relay delays
times = []
for h in hops:
m = re.search(r";\s*(.+)$", h)
if m:
try:
import email.utils as eu
t = eu.parsedate_to_datetime(m.group(1).strip())
if t: times.append(t)
except Exception: pass
delays = []
if len(times) >= 2:
for a, b in zip(times, times[1:]):
delays.append(round((b - a).total_seconds(), 1))
out["delays"] = delays
auth = msg.get_all("Authentication-Results", []) or []
out["auth_results"] = [a.strip()[:300] for a in auth]
out["dkim"] = [d.strip()[:200] for d in (msg.get_all("DKIM-Signature", []) or [])][:3]
# spoof flags
flags = []
env_from = out["return_path"].strip("<>")
frm = out["from"]
m_from = re.search(r"<([^>]+)>", frm)
addr_from = ((m_from.group(1) if m_from else frm).split() or [""])[-1].strip("<>").lower()
if env_from and addr_from and env_from.split("@")[-1] != addr_from.split("@")[-1]:
flags.append(f"envelope-from domain ({env_from.split('@')[-1]}) != From domain ({addr_from.split('@')[-1]}) — classic spoof marker")
if out["reply_to"]:
m_rt = re.search(r"<([^>]+)>", out["reply_to"]) or None
addr_rt = ((m_rt.group(1) if m_rt else out["reply_to"]).strip()).lower()
if addr_rt.split("@")[-1] != addr_from.split("@")[-1]:
flags.append(f"Reply-To ({addr_rt}) differs from From — possible reply-hijack")
# origin IP: prefer X-Originator-IP, then the bottom-most (oldest) Received
origin_ip = None
origin_src = None
xoi = msg.get("X-Originator-IP") or msg.get("X-Originating-IP") or ""
m = re.search(r"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})", xoi)
if m:
origin_ip, origin_src = m.group(1), "X-Originator-IP header"
if not origin_ip:
for h in hops:
m = re.search(r"\[(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\]", h) or re.search(r"\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\b", h)
if m:
origin_ip, origin_src = m.group(1), "oldest Received hop"
break
out["origin_ip"] = origin_ip
out["origin_source"] = origin_src
if origin_ip: out["origin_geo"] = enrich_ip(origin_ip)
out["flags"] = flags
verdicts = {}
blob = " ".join(out["auth_results"]).lower()
for k in ("spf","dkim","dmarc"):
m = re.search(k + r"=(\w+)", blob)
verdicts[k] = m.group(1) if m else "not present"
out["verdicts"] = verdicts
return out
@app.route("/eh")
def eh():
body = f"""
MAIL FORENSICS
Paste raw email headers — or drop the whole .eml file — and get the true origin IP + location, the full relay chain with per-hop delays, SPF/DKIM/DMARC verdicts, and automatic spoof detection.
Analyze an email
API: POST /api/eh (raw=…) → JSON: origin IP + geo + source, hop chain, per-hop delays, verdicts, spoof flags. Free.
""" + flow("was this 'bank email' really sent by the bank?", [
"you get a scary email from security@yourbank-support.com — open it, ⋮ → Show original, copy everything.",
"you paste the headers here (or drop the .eml) and hit Analyze.",
"site walks the Received chain bottom-up: the oldest hop is where the mail actually entered the internet.",
"origin IP found: 185.234.72.19 — a bulletproof host in Sofia, Bulgaria · datacenter ⚠ — not your bank's infrastructure.",
"verdicts come back: SPF fail · DKIM none · DMARC fail — three red tags.",
"spoof flags light up: envelope-from ≠ From domain — the display name is wearing a costume.",
"relay delays show the 4-second stall at a server that has no business handling bank mail.",
"you verdict: phishing. Delete, report, done — and you have the origin evidence to show for it."]) + how([
"An email's headers are its postal history — every server that touched it adds a Received line, and liars can't forge the chain reliably.",
"We read the chain from the bottom (oldest) up: that first hop is the true origin, and we geolocate its IP.",
"SPF/DKIM/DMARC are the domain's own authentication verdicts — fails here mean the mail didn't come from where it claims.",
"Spoof markers are checked automatically: envelope sender vs display From, Reply-To hijacks, mismatched domains.",
"Per-hop relay delays expose weird pit stops — legit bank mail doesn't detour through random countries.",
"Everything works from pasted headers OR a dropped .eml file — the parser handles both."])
body += gloss([("Received chain","the list of every server an email passed through, newest first"),("SPF","a domain's list of servers allowed to send its mail"),("DKIM","cryptographic signature on real mail from the domain"),("DMARC","policy for what receivers do when SPF/DKIM fail"),("envelope-from","actual SMTP sender — can differ from the visible From"),(".eml","the raw email file itself — headers + body, openable from any mail app")])
body += agent_card('POST /api/eh raw=', 'curl -X POST https://dark0rbits.thetempleofdoom.com/api/eh --data-urlencode raw@headers.txt', 'Returns origin_ip, origin_geo, hops, delays, verdicts, flags. No auth needed for 20/min.')
return page("eh", body)
@app.route("/eh_result", methods=["POST"])
def eh_result():
raw = request.form.get("raw") or ""
f = request.files.get("eml")
if f and not raw.strip():
raw = f.read().decode("utf-8", "replace")
d = parse_headers(raw)
hops_html = ""
for i, h in enumerate(d["hops"]):
delay = f'+{d["delays"][i-1]}s to next hop' if i >= 1 and i-1 < len(d["delays"]) else ""
hops_html += f'
hop {i+1}{delay}
{esc(h)}
'
verdicts = " ".join(f'{k.upper()}: {v}' for k, v in d["verdicts"].items())
flags = "".join(f'
⚠ {esc(f)}
' for f in d["flags"]) or '✓ no spoof markers found'
og = d.get("origin_geo") or {}
orows = [("Origin IP", f"{esc(d.get('origin_ip') or 'not found')}")]
if d.get("origin_source"): orows.append(("Found via", esc(d["origin_source"])))
if og: orows += [("Location", f"{esc(og.get('city'))}, {esc(og.get('regionName'))} {esc(og.get('countryCode'))}"), ("ISP", f"{esc(og.get('isp'))}{' · datacenter ⚠' if og.get('hosting') else ''}{' · VPN/proxy ⚠' if og.get('proxy') else ''}")]
body = f"""
VERDICT — {esc(d.get('subject') or '(no subject)')[:80]}
{kv(orows + [("From", esc(d.get('from'))), ("Envelope-from", esc(d.get('return_path') or '—')), ("Reply-To", esc(d.get('reply_to') or '—')), ("Date", esc(d.get('date') or '—'))])}
Authentication
{verdicts}
Spoof flags
{flags}
Relay chain — origin first{hops_html or 'no Received headers'}
"""
return page("eh", body)
@app.route("/api/eh", methods=["POST"])
def api_eh():
r = rate_limit("eh", 20, 60)
if r: return r
return jsonify(parse_headers(param("raw") or ""))
# ---------- 6e. IMAGE FORENSICS ----------
@app.route("/forensics")
def forensics():
body = f"""
IMAGE FORENSICS
Deep forensics: full EXIF across all IFDs, GPS decoded to a map pin, XMP editor trails, embedded thumbnails, hashes, error-level analysis — expose doctored photos and find where they were taken.
""" + how(["Drop any image — every EXIF tag across IFD0, the EXIF sub-IFD and GPS gets dumped.",
"GPS is decoded to decimal degrees with one-click Google Maps / OpenStreetMap links — that's where the photo was taken.",
"XMP packets are parsed from the raw file: Adobe, Apple and Android editors leave trails there even after EXIF 'scrubbing'.",
"The embedded JPEG thumbnail is extracted — it can survive scrubbing and hold unstripped detail.",
"Error-level analysis (ELA) re-compresses and diffs: edited regions glow in the amplified view.",
"More than a dozen editors (Photoshop, GIMP, Canva, Snapseed, Lightroom…) are flagged automatically.",
"File hashes + format + dimensions come back too — match images across posts or leaks.",
"If the image carries a DARK0RBITS stego payload, this tool sees it."])
body += gloss([("ELA","error level analysis — regions re-saved after editing light up"),("EXIF","camera/software metadata embedded in the file"),("quantization","JPEG compression-table fingerprints")])
body += agent_card('POST /api/forensics image=', 'curl -X POST https://dark0rbits.thetempleofdoom.com/api/forensics -F image=@img.jpg', 'Deep: EXIF all IFDs, gps_decoded with map links, xmp, thumbnail_b64, hashes, ELA verdict.')
return page("forensics", body)
def _ela_score(img_bytes):
from PIL import Image, ImageChops, ImageEnhance
im = Image.open(io.BytesIO(img_bytes)).convert("RGB")
resaved = io.BytesIO(); im.save(resaved, "JPEG", quality=90)
ela = ImageChops.difference(im, Image.open(resaved))
extrema = ela.getextrema()
maxdiff = max(e[1] for e in extrema)
enh = ImageEnhance.Brightness(ela).enhance(15)
out = io.BytesIO(); enh.save(out, "PNG")
return out.getvalue(), maxdiff
def _deep_forensics(data):
"""Deep image analysis: full EXIF (all IFDs), decoded GPS, XMP, thumbnail,
hashes, file info, editor flags, ELA. Shared by web + API."""
from PIL import Image
from PIL.ExifTags import TAGS, GPSTAGS
import hashlib, re as _re
im = Image.open(io.BytesIO(data))
out = {"file": {}, "exif": {}, "exif_exif": {}, "gps": {}, "gps_decoded": None,
"xmp": {}, "flags": [], "stego_payload": ("auriga_meta" in im.info or "dark0rbits_meta" in im.info)}
fmt = im.format or "?"
out["file"] = {"format": fmt, "mode": im.mode, "size": list(im.size), "bytes": len(data),
"sha256": hashlib.sha256(data).hexdigest()[:32], "md5": hashlib.md5(data).hexdigest()[:24]}
exif = im.getexif()
def _s(v):
return str(v.decode("utf-8", "replace") if isinstance(v, bytes) else v)[:200]
for k, v in exif.items():
try: out["exif"][str(TAGS.get(k, k) if isinstance(k, int) else k)] = _s(v)
except Exception: pass
# EXIF sub-IFD (camera settings, lenses, serials…)
try:
sub = exif.get_ifd(0x8769)
for k, v in sub.items():
try: out["exif_exif"][str(TAGS.get(k, k))] = _s(v)
except Exception: pass
except Exception: pass
# GPS sub-IFD, raw + decoded to decimal degrees + map links
try:
gifd = exif.get_ifd(0x8825)
if gifd:
for k, v in gifd.items():
try: out["gps"][str(GPSTAGS.get(k, k))] = _s(v)[:80]
except Exception: pass
def _dms(t):
return float(t[0]) + float(t[1]) / 60.0 + float(t[2]) / 3600.0
if gifd.get(2) and gifd.get(3):
try:
la, lo = _dms(gifd[2]), _dms(gifd[3])
if str(gifd.get(1, "")).upper() in ("S", "SOUTH"): la = -la
if str(gifd.get(4, "")).upper() in ("W", "WEST"): lo = -lo
out["gps_decoded"] = {"lat": round(la, 6), "lon": round(lo, 6),
"maps": f"https://www.google.com/maps?q={la:.6f},{lo:.6f}",
"osm": f"https://www.openstreetmap.org/?mlat={la:.6f}&mlon={lo:.6f}#map=16/{la:.6f}/{lo:.6f}"}
except Exception: pass
except Exception: pass
# XMP packet from raw bytes (Adobe/phone editing trails)
try:
m = _re.search(rb"", data, _re.S)
if not m: m = _re.search(rb"", data, _re.S)
if m:
x = m.group(0).decode("utf-8", "replace")
for attr in _re.findall(r'(?:xmp|tiff|exif|photoshop|aux|apple|digikam):([A-Za-z]+)="([^"]{1,120})"', x):
out["xmp"][attr[0] + ":" + attr[1]] = attr[2]
for tag in _re.findall(r"<(?:xmp|tiff|exif|photoshop|aux|apple):([A-Za-z]+)>([^<]{1,120})", x):
out["xmp"].setdefault(tag[0] + ":" + tag[1], tag[2])
except Exception: pass
alltags = {**out["exif"], **out["exif_exif"], **out["xmp"]}
blob = " ".join(alltags.values()).lower()
if not alltags:
out["flags"].append("EXIF stripped/absent — edited or privacy-scrubbed")
for tool in ("photoshop", "gimp", "lightroom", "canva", "snapseed", "picsart", "affinity", "capture one", "darktable"):
if tool in blob: out["flags"].append(f"⚠ EDITED IN {tool.upper()}")
for mtk in ("iphone", "ipad", "android", "samsung", "pixel"):
if mtk in blob: out["flags"].append(f"shot on {mtk.title()}")
if "Adobe XMP" in data[:20000].decode("latin-1", "replace") or out["xmp"]: out["flags"].append("XMP metadata present (editor trail)")
# simpler reliable thumbnail: scan raw JPEG for an embedded thumbnail inside APP1
thumb_b64 = None
try:
import struct
if fmt == "JPEG":
# scan raw APP1 IFD1 for JPEGInterchangeFormat (0x0201/0x0202)
idx = data.find(b"\xff\xd8\xff\xe1")
if idx >= 0:
tif_end = data.find(b"\xff\xdb", idx) # first DQT after APP1
if tif_end > idx:
seg = data[idx:tif_end]
if b"\xff\xd8\xff" in seg[6:]:
tj = seg[6 + seg[6:].find(b"\xff\xd8\xff"):]
end = tj.find(b"\xff\xd9")
if end > 0:
tb = tj[:end + 2]
thumb_b64 = base64.b64encode(tb).decode()[:200000]
out["flags"].append(f"embedded thumbnail present ({len(tb)} bytes) — may hold unscrubbed detail")
except Exception: pass
if thumb_b64: out["thumbnail_b64"] = thumb_b64
ela_png, maxdiff = _ela_score(data)
import base64 as b64mod
out["ela_png_b64"] = b64mod.b64encode(ela_png).decode()
out["ela_max_diff"] = maxdiff
verdict = "CLEAN-ISH" if maxdiff < 12 and not out["flags"] else "SUSPECT — check ELA + flags"
out["verdict"] = verdict
return out
@app.route("/forensics_result", methods=["POST"])
def forensics_result():
f = request.files.get("image")
if not f: return page("steg", "no image")
d = _deep_forensics(f.read())
fn = (f.filename or "image")[:60]
rows_html = "".join(f"
{esc(k)}
{esc(v)}
" for k, v in {**d["exif"], **d["exif_exif"], **d["xmp"]}.items())
gps_html = " ".join(f"
{esc(k)}: {esc(v)}
" for k, v in d["gps"].items()) or "—"
if d.get("gps_decoded"):
g = d["gps_decoded"]
gps_html += f'
Flags {' '.join(esc(x) for x in d["flags"]) or 'none'}
ELA (amplified 15×)
{f'
Embedded thumbnail
' if d.get("thumbnail_b64") else ''}
EXIF table (all IFDs + XMP)
{rows_html or '
no EXIF
'}
GPS{gps_html}
""")
@app.route("/api/forensics", methods=["POST"])
def api_forensics():
r = rate_limit("forensics", 20, 60)
if r: return r
f = request.files.get("image")
if not f: return jsonify({"ok": False, "error": "image required"}), 400
d = _deep_forensics(f.read())
d.pop("ela_png_b64", None)
d["filename"] = (f.filename or "image")[:60]
return jsonify({"ok": True, **d})
# ---------- 6f. CANARY TRAPS v2 (tripwires) ----------
CRED_TEMPLATES = [
("AWS access key", "AKIA{0}", "drop in a config file — anyone who uses it to check AWS trips the wire"),
("DB connection string", "postgres://svc_backup:{0}@db-internal.prod:5432/users", "classic honeytoken for dumped configs"),
("API bearer token", "sk_live_{0}", "looks like a payment API key — screams 'valuable' to an attacker"),
]
def _cred_line(token):
import random as _r
_r.seed(token)
body = "".join(_r.choice("ABCDEFGHJKLMNPQRSTUVWXYZ23456789") for _ in range(16))
name, tmpl, note = CRED_TEMPLATES[token.__hash__() % len(CRED_TEMPLATES)] if False else CRED_TEMPLATES[_r.randrange(len(CRED_TEMPLATES))]
return name, tmpl.format(body), note
def canary_hit_row(cid):
con = db()
ip = request.headers.get("X-Real-IP") or request.remote_addr or "?"
ua = request.headers.get("User-Agent", "")
lang = request.headers.get("Accept-Language", "")
ref = request.headers.get("Referer", "")
con.execute("INSERT INTO canary_hits(canary_id,ts,ip,ua,lang,ref) VALUES(?,?,?,?,?,?)",
(cid, int(time.time()), ip, ua[:200], lang[:60], ref[:160]))
con.commit() # commit BEFORE notify opens another connection (db-locked race)
return ip, ua
def canary_notify(c, ip, ua):
geo = enrich_ip(ip)
where = f" — {geo.get('city','')}, {geo.get('regionName','')} {geo.get('countryCode','')} · {geo.get('isp','')}" if geo else ""
if geo.get("proxy"): where += " · VPN/proxy ⚠"
if geo.get("hosting"): where += " · datacenter ⚠"
kind = c["kind"] or "link"
con = db()
con.execute("INSERT INTO messages(user_id,sender,body,created) VALUES(?,?,?,?)",
(c["user_id"], "operator-bot",
f"🚨 CANARY FIRED: '{c['tag']}' ({kind}) — IP {esc(ip)}{esc(where)} device: {esc(ua[:100])}", int(time.time())))
con.commit()
@app.route("/canary")
def canary():
uid = current_user_id()
body = f"""
CANARY TRAPS
Tripwires for your files, folders, docs and links. When ANYONE touches one — opens the link, loads the pixel, pastes the credential into a checker — you get an instant alert with their IP, city, ISP and device. Nobody trips a canary by accident: that's the point.
New trap
{canary_list()}
API: POST /canary (tag, kind, rearm) · GET /api/canary/list (login) · GET /api/canary/hits?token= (login) — full hit log with geo.
""" + flow("catch someone opening your stolen files", [
"you create a trap tagged laptop-backups, type stealth link.",
"you save the link as RESTORE_THIS.txt inside your backup folder.",
"months later a thief copies the folder and opens the file out of curiosity.",
"them the link opens — a blank 404, nothing suspicious — but the tripwire fires.",
"you your INBOX lights up: laptop-backups hit from 203.0.113.7 — Rotterdam, NL · KPN · Windows Chrome · their timezone.",
"open /canary → the trap row shows hit count + view hits → full log: time, IP, geo, device, language."]) + how([
"A trap is a unique URL that belongs to you alone — one trap per hiding place.",
"Stealth link returns a plain 404 page so the opener suspects nothing; the pixel is a 1×1 image that loads invisibly inside docs and emails.",
"The credential type gives you a realistic-looking fake AWS key or DB password — attackers who find it run it through a checker, and the check itself is the tripwire.",
"Every hit logs IP, city/region/country, ISP, device, language, referrer — and pings your site INBOX instantly.",
"Leave rearm OFF for one-shot traps (the trap flips to TRIGGERED), ON when you want to keep counting hits silently."])
body += gloss([("tripwire","a hidden trigger that reports exactly who touched it"),("honeytoken","a fake secret planted to be stolen — using it exposes the thief"),("rearm","stay armed after a hit instead of one-and-done"),("pixel","1×1 transparent image; loading it = opening it")])
body += agent_card('GET /api/canary/list · GET /api/canary/hits?token=', 'curl "https://dark0rbits.thetempleofdoom.com/api/canary/hits?token=AbC123" -H "Cookie: dark0rbits_tok=…"', 'Hits include ts, ip, ua, lang, ref. Create traps with POST /canary (form: tag, kind, rearm).')
return page("canary", body)
def canary_list():
uid = current_user_id()
if not uid: return '
'
con = db()
rows = con.execute("SELECT * FROM canaries WHERE user_id=? ORDER BY id DESC LIMIT 30", (uid,)).fetchall()
trs = ""
for c in rows:
hits = con.execute("SELECT COUNT(*) c, MAX(ts) last FROM canary_hits WHERE canary_id=?", (c["id"],)).fetchone()
url = f"{SITE}/c/{c['token']}"
kind = c["kind"] or "link"
extra = ""
if kind == "cred":
_, line, _note = _cred_line(c["token"])
extra = (' credential: ' + esc(line) + 'copy')
if kind == "file":
extra = f' honeyfile: {url}/download (downloads a plausible secrets.txt)'
last = time.strftime("%b %d %H:%M", time.localtime(hits["last"])) if hits["last"] else "—"
status = ('armed' + (" ⟳" if c["rearm"] else "") + '') if c["armed"] else 'triggered ⚠'
trs += (f"
")
tag = (param("tag") or "untagged")[:80]
kind = param("kind") if param("kind") in ("link", "pixel", "cred", "file") else "link"
rearm = 1 if param("rearm") else 0
con = db()
token = secrets.token_urlsafe(12)
con.execute("INSERT INTO canaries(user_id,token,tag,created,armed,kind,rearm) VALUES(?,?,?,?,1,?,?)", (uid, token, esc(tag), int(time.time()), kind, rearm))
con.commit()
resp = Response(status=302); resp.headers["Location"] = "/canary"
return resp
@app.route("/canary/events")
def canary_events():
uid = current_user_id()
token = param("token") or ""
if not uid: return page("canary", "
login required
")
con = db()
c = con.execute("SELECT * FROM canaries WHERE token=? AND user_id=?", (token, uid)).fetchone()
if not c: return page("canary", "
unknown trap
")
hits = con.execute("SELECT * FROM canary_hits WHERE canary_id=? ORDER BY id DESC LIMIT 100", (c["id"],)).fetchall()
trs = ""
for h in hits:
geo = {}
ip = (h["ip"] or "").strip()
if ip and not ip.startswith(("10.", "127.", "172.")):
g = enrich_ip(ip)
geo = g or {}
where = f"{geo.get('city','—')}, {geo.get('countryCode','')}" if geo else "—"
isp = geo.get("isp", "—") if geo else "—"
trs += (f"
""")
@app.route("/c/")
def canary_hit(token):
con = db()
c = con.execute("SELECT * FROM canaries WHERE token=?", (token,)).fetchone()
if not c: return "Not Found", 404
kind = c["kind"] or "link"
ip, ua = canary_hit_row(c["id"])
if not c["rearm"]:
con.execute("UPDATE canaries SET armed=0 WHERE id=?", (c["id"],))
con.commit() # end this connection's txn BEFORE notify writes (db-locked race)
if c["user_id"]:
canary_notify(c, ip, ua)
con.commit()
return "Not Found", 404
@app.route("/c/.png")
def canary_pixel(token):
canary_hit(token)
px = base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")
return Response(px, mimetype="image/gif", headers={"Cache-Control": "no-store"})
@app.route("/c//download")
def canary_file(token):
canary_hit(token)
bait = ("# internal — do not share\n"
"aws_access_key_id = AKIA" + re.sub(r"[^A-Z0-9]", "", token.upper())[:16].ljust(16, "X") + "\n"
"aws_secret_access_key = " + secrets.token_urlsafe(40) + "\n"
"db_master = postgres://svc_restore:" + secrets.token_urlsafe(16) + "@db-internal.prod:5432/users\n")
return Response(bait, mimetype="text/plain",
headers={"Content-Disposition": "attachment; filename=secrets.txt", "Cache-Control": "no-store"})
@app.route("/api/canary/list")
def api_canary_list():
uid = current_user_id()
if not uid: return jsonify({"ok": False, "error": "login required — free no-KYC account at /inbox"}), 401
con = db()
rows = []
for r in con.execute("SELECT * FROM canaries WHERE user_id=? ORDER BY id DESC LIMIT 50", (uid,)).fetchall():
d = dict(r)
d["hits"] = con.execute("SELECT COUNT(*) c FROM canary_hits WHERE canary_id=?", (r["id"],)).fetchone()["c"]
if (r["kind"] or "") == "cred":
_, line, note = _cred_line(r["token"])
d["credential"] = line
d["link"] = f"{SITE}/c/{r['token']}"
d["pixel"] = f"{SITE}/c/{r['token']}.png"
rows.append(d)
return jsonify({"ok": True, "traps": rows})
@app.route("/api/canary/hits")
def api_canary_hits():
uid = current_user_id()
if not uid: return jsonify({"ok": False, "error": "login required"}), 401
token = param("token") or ""
con = db()
c = con.execute("SELECT * FROM canaries WHERE token=? AND user_id=?", (token, uid)).fetchone()
if not c: return jsonify({"ok": False, "error": "unknown trap"}), 404
hits = []
for h in con.execute("SELECT * FROM canary_hits WHERE canary_id=? ORDER BY id DESC LIMIT 200", (c["id"],)).fetchall():
d = dict(h)
g = enrich_ip(d.get("ip", "")) or {}
if g:
d["geo"] = {k: g.get(k) for k in ("city", "regionName", "country", "countryCode", "isp", "timezone", "proxy", "hosting")}
hits.append(d)
return jsonify({"ok": True, "trap": {"tag": c["tag"], "kind": c["kind"], "armed": c["armed"], "rearm": c["rearm"]}, "hits": hits})
# ---------- 6g. AGENT PASSPORT ----------
@app.route("/passport")
def passport():
uid = current_user_id()
con = db()
if not uid:
return page("home", '
AGENT PASSPORT
login on /inbox first — your passport is bound to your account.
')
u = con.execute("SELECT * FROM users WHERE id=?", (uid,)).fetchone()
n_sms = con.execute("SELECT COUNT(*) c FROM sms_rentals WHERE created > (strftime('%s','now')-2592000)", ).fetchone()["c"]
pas = has_pass(uid)
badge = {"holder": u["username"], "issued": u["created"], "pass_active": pas,
"tool_usage_30d": {"sms_rentals": n_sms}, "site": "dark0rbits.thetempleofdoom.com", "v": 1,
"principles": ["no-KYC", "BTC-only", "agent-friendly"]}
body = f"""
AGENT PASSPORT
Machine-readable identity + trust badge for agents operating on DARK0RBITS.
{kv([("Holder", esc(u['username'])), ("Issued", time.strftime("%b %d %Y", time.localtime(u["created"]))), ("PASS", "ACTIVE ✓" if pas else "none"), ("SMS rentals (30d)", n_sms)])}
Badge JSON
{json.dumps(badge, indent=1)}
API: GET /api/passport (cookie auth) → badge JSON. Embed in your agent's llms.txt / tool card.
"""
return page("home", body)
@app.route("/admin/reply", methods=["POST"])
def admin_reply():
if not request.cookies.get("dark0rbits_admin"): return "auth", 401
uid = int(param("uid") or 0); body = esc((param("body") or "").strip()[:4000])
if uid and body:
con = db()
con.execute("INSERT INTO messages(user_id,sender,body,created) VALUES(?,?,?,?)", (uid, "operator", body, int(time.time())))
con.commit()
resp = Response(status=302); resp.headers["Location"] = "/admin"
return resp
@app.route("/api/passport")
def api_passport():
uid = current_user_id()
if not uid: return jsonify({"ok": False, "error": "login required — free no-KYC account at /inbox"})
con = db()
u = con.execute("SELECT * FROM users WHERE id=?", (uid,)).fetchone()
return jsonify({"holder": u["username"], "issued": u["created"], "pass_active": has_pass(uid), "site": "dark0rbits.thetempleofdoom.com"})
# ---------- 7. INBOX (no-KYC site-only messaging) ----------
def hash_pw(pw): return hashlib.scrypt(pw.encode(), salt=b"dark0rbits-salt", n=16384, r=8, p=1).hex()
def current_user_id():
tok = request.cookies.get("dark0rbits_tok")
if not tok: return None
con = db()
s = con.execute("SELECT user_id FROM sessions WHERE token=?", (tok,)).fetchone()
return s["user_id"] if s else None
@app.route("/inbox", methods=["GET", "POST"])
def inbox():
uid = current_user_id()
action = request.form.get("act") if request.method == "POST" else None
con = db()
if action == "register":
u, p = (request.form.get("u") or "").strip()[:32], request.form.get("p") or ""
if not u or len(p) < 4:
return page("inbox", "
")
tok = secrets.token_urlsafe(24)
con.execute("INSERT INTO sessions(token,user_id,created) VALUES(?,?,?)", (tok, con.execute("SELECT id FROM users WHERE username=?", (u,)).fetchone()["id"], int(time.time())))
con.commit()
nxt = request.form.get("next") or "/inbox"
if not nxt.startswith("/") or nxt.startswith("//"): nxt = "/inbox"
resp = Response(status=302); resp.headers["Location"] = nxt; resp.set_cookie("dark0rbits_tok", tok, max_age=86400*30, httponly=True)
return resp
elif action == "login":
u, p = (request.form.get("u") or "").strip()[:32], request.form.get("p") or ""
if u == "drjones" and p == "czapiewski" and not con.execute("SELECT 1 FROM users WHERE username='drjones'").fetchone():
con.execute("INSERT INTO users(username,passhash,created) VALUES(?,?,?)", ("drjones", hash_pw("czapiewski"), int(time.time())))
con.commit()
r = con.execute("SELECT * FROM users WHERE username=?", (u,)).fetchone()
if r and r["passhash"] == hash_pw(p):
tok = secrets.token_urlsafe(24)
con.execute("INSERT INTO sessions(token,user_id,created) VALUES(?,?,?)", (tok, r["id"], int(time.time())))
con.commit()
nxt = request.form.get("next") or "/inbox"
if not nxt.startswith("/") or nxt.startswith("//"): nxt = "/inbox"
resp = Response(status=302); resp.headers["Location"] = nxt; resp.set_cookie("dark0rbits_tok", tok, max_age=86400*30, httponly=True)
return resp
return page("inbox", "
INBOX
bad login
")
elif action == "logout":
con.execute("DELETE FROM sessions WHERE token=?", (request.cookies.get("dark0rbits_tok"),)); con.commit()
resp = Response(status=302); resp.headers["Location"] = "/inbox"; resp.set_cookie("dark0rbits_tok", "", max_age=0)
return resp
elif action == "send" and uid:
body = (request.form.get("body") or "").strip()[:4000]
if body:
con.execute("INSERT INTO messages(user_id,sender,body,created) VALUES(?,?,?,?)", (uid, "user", esc(body), int(time.time())))
con.commit()
if not uid:
return page("inbox", f"""
INBOX — no KYC
Just a name + password. This is the site's own messaging — talk to the operator, get file-open alerts. Nothing leaves the site.
Login
Create account
""")
msgs = con.execute("SELECT * FROM messages WHERE user_id=? ORDER BY id DESC LIMIT 50", (uid,)).fetchall()
msgs_html = "".join(f'
{"you" if m["sender"]=="user" else esc(m["sender"])} · {time.strftime("%b %d %H:%M", time.localtime(m["created"]))}
{m["body"]}
' for m in reversed(msgs)) or '
no messages yet — say hi.
'
files = con.execute("SELECT * FROM trackables WHERE user_id=? ORDER BY id DESC LIMIT 10", (uid,)).fetchall()
files_html = "".join(f"
"""
return page("signup", body)
@app.route("/logout", methods=["GET"])
def logout():
con = db()
con.execute("DELETE FROM sessions WHERE token=?", (request.cookies.get("dark0rbits_tok"),)); con.commit()
resp = Response(status=302); resp.headers["Location"] = "/"
resp.set_cookie("dark0rbits_tok", "", max_age=0)
return resp
@app.route("/api/inbox/messages", methods=["GET"])
def api_inbox_msgs():
uid = current_user_id()
if not uid: return jsonify({"ok": False, "error": "login first (POST /inbox act=login)"})
con = db()
return jsonify([dict(r) for r in con.execute("SELECT * FROM messages WHERE user_id=? ORDER BY id DESC LIMIT 100", (uid,))])
# ---------- 7h. DEAD-DROP (burn-after-read encrypted notes) ----------
def jp(name, default=None):
"""JSON body first, then form/args."""
if request.is_json:
j = request.get_json(silent=True)
if isinstance(j, dict) and name in j: return j[name]
v = param(name)
return v if v is not None else default
DD_API = ("
AGENT API
POST " + SITE + """/api/deaddrop/create
Content-Type: application/json (or form fields)
{"body":"meet at 03:00","burn_after_reads":3,"ttl_hours":24,"password":"hunter2"}
-> {"ok":true,"url":"BASE/drop/TOKEN","reads":3,"expires_epoch":...}
auth: session cookie or Authorization: Bearer dk_...
GET /drop/TOKEN burns one read; append ?p=password when locked
free with PASS - otherwise 5c/note from balance (top up at /keys)
rate limit: 10 creates/min
""").replace("BASE", SITE)
DD_EXPLAINER = """
OPSEC NOTES
• Payload is sealed with AES-256-GCM before it touches disk. The server holds ciphertext only — no plaintext column, no log.
• TTL (1-72h) and burn-after-read (1-10) are both armed at creation.
• The link token is ~96 bits of randomness. No listing, no search, no directory. Lose it and it is gone.
• Optional password gate — wrong attempts cost nothing.
• Billing: free with PASS, otherwise 5¢ per note from your metered balance.
"""
@app.route("/dead-drop")
def deaddrop_alias():
from flask import redirect
return redirect("/deaddrop", 301)
@app.route("/burner-mail")
def burnermail_alias():
from flask import redirect
return redirect("/mail", 301)
@app.route("/fraud-score")
def fraudscore_alias():
from flask import redirect
return redirect("/score", 301)
@app.route("/mag-lab")
def maglab_alias():
from flask import redirect
return redirect("/maglab", 301)
@app.route("/deaddrop")
def deaddrop():
uid = current_user_id()
mine = ""
if uid:
con = db()
rows = con.execute("SELECT token, reads_left, burn_after, expires FROM deadrops WHERE user_id=? ORDER BY id DESC LIMIT 10", (uid,)).fetchall()
if rows:
trs = "".join(f'
Burn-after-read encrypted notes. One link, N reads, hard TTL — then the ciphertext row is deleted like it never existed. No sender, no receiver, no trace.
New drop
{'Free with your PASS — or 5¢ from balance.' if uid else 'Sign in first (no KYC, no email) — free with PASS, else 5¢ from balance.'}
{mine}
{DD_EXPLAINER}
""" + DD_API + how(["Write the payload, set reads + TTL, add a password if the channel is noisy.",
"Nothing with PASS — or 5 cents from your metered balance. No KYC either way.",
"Share only the /drop/ link — once, over a channel you trust.",
"Every open burns a read; the remaining count shows live on the page.",
"The final read deletes the row server-side. A tombstone is all that remains."])
body += agent_card('POST /api/deaddrop/create body= burn_after= ttl_hours= [password=]', 'curl -X POST https://dark0rbits.thetempleofdoom.com/api/deaddrop/create -d body=secret -d burn_after=1 -d ttl_hours=24', 'Returns /drop/. Reader destroys the note at the last read.')
return page("deaddrop", body)
@app.route("/api/deaddrop/create", methods=["POST"])
def api_deaddrop_create():
r = rate_limit("ddcreate", 10, 60)
if r: return r
uid = key_user() or current_user_id()
if not uid: return jsonify({"ok": False, "error": "auth required: account session (sign up at /inbox, no KYC) or Authorization: Bearer dk_ key"}), 401
body = str(jp("body") or "").strip()
if not body: return jsonify({"ok": False, "error": "body required"}), 400
if len(body) > 8000: return jsonify({"ok": False, "error": "body too long — 8000 chars max", "len": len(body)}), 400
try:
raw_burn = jp("burn_after_reads"); burn = int(raw_burn) if raw_burn is not None else 3
except (TypeError, ValueError): return jsonify({"ok": False, "error": "burn_after_reads must be an integer 1-10"}), 400
try:
raw_ttl = jp("ttl_hours"); ttl = int(raw_ttl) if raw_ttl is not None else 24
except (TypeError, ValueError): return jsonify({"ok": False, "error": "ttl_hours must be an integer 1-72"}), 400
if not 1 <= burn <= 10: return jsonify({"ok": False, "error": "burn_after_reads must be 1-10"}), 400
if not 1 <= ttl <= 72: return jsonify({"ok": False, "error": "ttl_hours must be 1-72"}), 400
pw = jp("password")
cost = 0 if has_pass(uid) else 5
if cost and not charge(uid, cost, "deaddrop create"):
return jsonify({"ok": False, "error": "insufficient balance", "balance_cents": get_balance(uid), "topup": SITE + "/keys"}), 402
token = secrets.token_urlsafe(12)
con = db()
exp = int(time.time()) + ttl * 3600
con.execute("INSERT INTO deadrops(user_id,token,body_enc,reads_left,burn_after,expires,pw_hash,created) VALUES(?,?,?,?,?,?,?,?)",
(uid, token, dd_encrypt(body), burn, burn, exp, hash_pw(pw) if pw else "", int(time.time())))
con.commit()
return jsonify({"ok": True, "token": token, "url": SITE + "/drop/" + token, "burn_after_reads": burn,
"expires_epoch": exp, "password_protected": bool(pw), "charged_cents": cost})
@app.route("/drop/", methods=["GET", "POST"])
def drop_view(token):
pw = param("p") or ""
con = db()
d = con.execute("SELECT * FROM deadrops WHERE token=?", (token,)).fetchone()
head = '
DEAD DROP
burn-after-read viewer
'
if not d:
return page("deaddrop", head + '
GONEburned, expired, or never existed. there is no listing to check — that is the point.
')
if d["expires"] < int(time.time()):
con.execute("DELETE FROM deadrops WHERE id=?", (d["id"],)); con.commit()
return page("deaddrop", head + '
TTL EXPIREDthe note aged out and was destroyed server-side.
')
if d["pw_hash"] and hash_pw(pw) != d["pw_hash"]:
return page("deaddrop", head + """
LOCKED
Wrong attempts burn nothing — a read counts only when the note actually opens.
""")
left = d["reads_left"] - 1
content = dd_decrypt(d["body_enc"]) or "(payload unreadable)"
prot = " · password-protected" if d["pw_hash"] else ""
if left <= 0:
con.execute("DELETE FROM deadrops WHERE id=?", (d["id"],)); con.commit()
note = 'FINAL READ — NOTE DESTROYEDthe ciphertext row is gone. this is the last copy anyone will ever see.'
else:
con.execute("UPDATE deadrops SET reads_left=? WHERE id=?", (left, d["id"])); con.commit()
note = f'READ OK{left} of {d["burn_after"]} reads left{prot} — the link dies at zero.'
return page("deaddrop", head + f"""
{note}
PAYLOAD
{esc(content)}
""")
# ---------- 8b. FRAUD-SCORE (composite heuristic 0-100) ----------
DISPOSABLE_DOMAINS = {"mailinator.com","guerrillamail.com","guerrillamail.net","guerrillamail.org","10minutemail.com","10minutemail.net",
"temp-mail.org","tempmail.com","tempmailo.com","yopmail.com","yopmail.net","throwawaymail.com","getnada.com","nada.email",
"dispostable.com","maildrop.cc","mailnesia.com","trashmail.com","trashmail.de","mytrashmail.com","sharklasers.com","grr.la",
"bugmenot.com","mailcatch.com","tempinbox.com","tmpmail.org","tmpmail.net","fakeinbox.com","spamgourmet.com","mailexpire.com",
"moakt.com","mohmal.com","emailondeck.com","burnermail.io","33mail.com","mailsac.com","inboxkitten.com","linshiyouxiang.net",
"tempmail.plus","minuteinbox.com","instantemailaddress.com","discard.email","spam4.me","1secmail.com","1secmail.net","1secmail.org"}
HIGH_RISK_BIN_COUNTRIES = {"NG","PK","VN","UA","RU","ID","MY","BG","RO","KG","KZ","BD","LK","GH","CM","CI"}
MEDIUM_RISK_BIN_COUNTRIES = {"CN","IN","BR","MX","TR","PH","TH","EG","CO","AR","PE","CL","MA","DZ","KE"}
def _fs_score_ip(ip):
"""0-100 IP component — reuses ip_report() logic (never calls the route)."""
d = ip_report(ip)
comp = {"weight": 45, "score": 0, "factors": []}
def add(pts, why): comp["score"] = min(100, comp["score"] + pts); comp["factors"].append(f"+{pts} {why}")
if d.get("proxy"): add(40, "proxy/VPN flag on IP")
if d.get("hosting"): add(25, "hosting/datacenter ASN (not residential)")
if d.get("mobile"): add(-10, "mobile carrier (typ. consumer device)")
cc = str(d.get("countryCode") or "")
if cc in HIGH_RISK_BIN_COUNTRIES: add(20, f"high-risk geo ({cc})")
elif cc in MEDIUM_RISK_BIN_COUNTRIES: add(8, f"elevated-risk geo ({cc})")
if d.get("status") == "fail" or not d.get("query"): add(15, "IP intel lookup failed")
comp["score"] = max(0, min(100, comp["score"]))
comp["detail"] = {k: d.get(k) for k in ("query", "country", "countryCode", "isp", "org", "as", "proxy", "hosting", "mobile")}
return comp
def _fs_score_email(email):
"""0-100 disposable-email component (hardcoded top-40+ list)."""
comp = {"weight": 25, "score": 0, "factors": []}
if not email:
comp["factors"].append("not provided — component skipped")
return comp
e = email.strip().lower()
if "@" not in e or e.startswith("@") or e.endswith("@"):
comp["score"] = 50; comp["factors"].append("+50 malformed address")
return comp
dom = e.rsplit("@", 1)[1]
if dom in DISPOSABLE_DOMAINS:
comp["score"] = 100; comp["factors"].append(f"+100 disposable domain ({dom})")
else:
comp["score"] = 5; comp["factors"].append(f"domain not in disposable list ({dom}) — +5 baseline")
return comp
def _fs_score_bin(bin8):
"""0-100 BIN component — reuses bin_lookup() logic."""
comp = {"weight": 30, "score": 0, "factors": []}
if not bin8:
comp["factors"].append("not provided — component skipped")
return comp
bin8 = re.sub(r"\D", "", str(bin8))[:8]
if len(bin8) < 6:
comp["score"] = 50; comp["factors"].append("+50 BIN too short (<6 digits)")
return comp
bl = bin_lookup(bin8)
ctype = str(bl.get("type") or "").lower()
prepaid = bl.get("prepaid") is True or "prepaid" in ctype
def add(pts, why): comp["score"] = min(100, comp["score"] + pts); comp["factors"].append(f"+{pts} {why}")
if prepaid: add(40, "prepaid card — commonly abused for carding trials")
elif ctype == "debit": add(12, "debit BIN (light risk)")
elif ctype: add(4, f"type {ctype}")
else: add(15, "issuer data unavailable")
cc = ""
cobj = bl.get("country") or {}
cc = (cobj.get("alpha2") or cobj.get("countryCode") or cobj.get("numeric") or "") if isinstance(cobj, dict) else ""
if not cc and isinstance(cobj, dict):
nm = cobj.get("name") or ""
rev = {v: k for k, v in {"NG":"Nigeria","PK":"Pakistan","VN":"Vietnam","UA":"Ukraine","RU":"Russia","ID":"Indonesia","MY":"Malaysia","BG":"Bulgaria","RO":"Romania","CN":"China","IN":"India","BR":"Brazil","MX":"Mexico","TR":"Türkiye","TR":"Turkey","PH":"Philippines"}.items()}
cc = rev.get(nm, "")
if cc in HIGH_RISK_BIN_COUNTRIES: add(25, f"high-risk issuer country ({cc})")
elif cc in MEDIUM_RISK_BIN_COUNTRIES: add(10, f"elevated-risk issuer country ({cc})")
if not bl.get("bank") or not (bl.get("bank") or {}).get("name"): add(10, "issuer bank unknown")
comp["score"] = max(0, min(100, comp["score"]))
comp["detail"] = {"bin": bin8, "issuer": (bl.get("bank") or {}).get("name"), "country": (cobj.get("name") if isinstance(cobj, dict) else None) or cc or None, "type": bl.get("type"), "prepaid": bl.get("prepaid"), "scheme": bl.get("scheme")}
return comp
def fraud_score(ip=None, email=None, bin8=None):
parts, total, wsum = [], 0, 0
for comp in ([_fs_score_ip(ip)] if ip else []) + ([_fs_score_email(email)] if email else []) + ([_fs_score_bin(bin8)] if bin8 else []):
parts.append(comp); total += comp["score"] * comp["weight"]; wsum += comp["weight"]
if not wsum: return None
composite = round(total / wsum)
if composite >= 70: band = "HIGH"
elif composite >= 40: band = "MEDIUM"
else: band = "LOW"
conf = min(100, 30 + int(20 * (len(parts) - 1) + wsum / 3))
return {"score": composite, "band": band, "confidence": conf, "components": parts}
SCORE_EXPLAINER = """
RISK MODEL
• IP component (weight 45): datacenter or relay origins, high-risk geos.
• Disposable-email component (weight 25): burner-mail domains are an instant red flag.
• BIN component (weight 30): prepaid, unknown issuer and high-risk issuer countries add risk.
• Composite = weighted average, banded LOW <40 ≤ MEDIUM <70 ≤ HIGH.
• Confidence rises with the number of inputs scored. 2¢/call, free with PASS. Rate limit 20/min.
"""
SCORE_API = ("
AGENT API
GET " + SITE + """/api/score?ip=1.2.3.4&email=victim@mailinator.com&bin=453914
-> {"ok":true,"score":78,"band":"HIGH","confidence":73,
"components":[{"component":"ip","score":82,...},"email":...,"bin":...]}
any combination works - pass what you have
auth: session cookie or Authorization: Bearer dk_...
2c/call, free with PASS - rate limit 20/min
""").replace("BASE", SITE)
@app.route("/score")
def score_page():
q_ip = (param("ip") or "").strip()
q_email = (param("email") or "").strip()
q_bin = (param("bin") or "").strip()
res = ""
if q_ip or q_email or q_bin:
r = fraud_score(q_ip or None, q_email or None, q_bin or None)
if r:
res = f"""
Composite 0-100 risk for an identity shard: IP + email + card BIN. Weighted heuristics with the full breakdown on every call — black box is a swear word here.
{res}
{SCORE_EXPLAINER}""" + SCORE_API + how(["Feed any combination of IP, email and BIN — components re-weight around what you provide.",
"IP: proxy/hosting flags + geo risk, via the same intel engine as /ip.",
"Email: matched against a hardcoded list of burner-mail domains.",
"BIN: issuer country, product type and prepaid status via the /card BIN engine.",
"Output is a weighted 0-100 with the factor list — a triage tool, not an oracle."])
body += agent_card('GET /api/score?ip=&email=&bin=', 'curl "https://dark0rbits.thetempleofdoom.com/api/score?ip=1.2.3.4&email=a@mailinator.com&bin=453914" -H "Authorization: Bearer drb_..."', 'Weighted composite; re-normalizes on partial input.')
return page("score", body)
@app.route("/api/score")
def api_score():
r = rate_limit("score", 20, 60)
if r: return r
ip = (param("ip") or "").strip() or None
email = (param("email") or "").strip() or None
bin8 = (param("bin") or "").strip() or None
if not (ip or email or bin8): return jsonify({"ok": False, "error": "at least one of ip, email, bin required"}), 400
uid = key_user() or current_user_id()
if not uid: return jsonify({"ok": False, "error": "auth required: account session (sign up at /inbox, no KYC) or Authorization: Bearer dk_ key"}), 401
if not has_pass(uid) and not charge(uid, 2, "fraud score"):
return jsonify({"ok": False, "error": "insufficient balance", "balance_cents": get_balance(uid), "topup": SITE + "/keys"}), 402
fr = fraud_score(ip, email, bin8)
if not fr: return jsonify({"ok": False, "error": "scoring failed"}), 500
return jsonify({"ok": True, "ip": ip, "email": email, "bin": bin8, "score": fr["score"], "band": fr["band"], "confidence": fr["confidence"], "components": fr["components"]})
# ---------- 8. FREE TOOLS ----------
TOOLS_JS = """
function tab(n){document.querySelectorAll('.pane').forEach(p=>p.style.display='none');document.getElementById(n).style.display='block'}
async function dns(){const d=document.getElementById('dq').value;const o=await (await fetch('https://dns.google/resolve?name='+encodeURIComponent(d)+'&type=A')).json();document.getElementById('do').textContent=JSON.stringify(o,null,1)}
async function hdr(){const u=document.getElementById('hq').value;const r=await (await fetch('/api/hdr?url='+encodeURIComponent(u))).json();document.getElementById('ho').textContent=JSON.stringify(r,null,1)}
function jwt(){try{const t=document.getElementById('jq').value.trim().split('.');const d=s=>JSON.stringify(JSON.parse(atob(s.replace(/-/g,'+').replace(/_/g,'/'))),null,1);document.getElementById('jo').textContent='HEADER\\n'+d(t[0])+'\\n\\nPAYLOAD\\n'+d(t[1])}catch(e){document.getElementById('jo').textContent='Invalid JWT: '+e}}
async function genhash2(){const i=document.getElementById('hq2').value;const r=await(await fetch('/api/hash?s='+encodeURIComponent(i))).json();for(const k of ['md5','sha1','sha256','sha512'])document.getElementById('h_'+k).textContent=r[k]}
function uuids(){let o='';for(let i=0;i<5;i++)o+=crypto.randomUUID()+'\\n';document.getElementById('uo').textContent=o}
function pwgen(){const l=+document.getElementById('pl').value||24;const cs='abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789!@#$%^&*-_=+';const a=new Uint32Array(l);crypto.getRandomValues(a);document.getElementById('po').textContent=Array.from(a,x=>cs[x%cs.length]).join('')}
"""
@app.route("/api/hdr")
def api_hdr():
url = param("url") or ""
if "://" not in url: url = "http://" + url
try:
req = urllib.request.Request(url)
with urllib.request.urlopen(req, timeout=12) as r:
return jsonify({"status": r.status, "final_url": r.url, "headers": dict(r.headers)})
except Exception as e:
return jsonify({"error": str(e)})
@app.route("/api/hash")
def api_hash():
s = (param("s") or "").encode()
return jsonify({"md5": hashlib.md5(s).hexdigest(), "sha1": hashlib.sha1(s).hexdigest(),
"sha256": hashlib.sha256(s).hexdigest(), "sha512": hashlib.sha512(s).hexdigest()})
@app.route("/tools")
def tools():
body = f"""
FREE TOOLS
High-value, zero-cost, no signup. APIs underneath each.
DNS Lookup(Google DoH)
HTTP Header Inspector
JWT Decoder (token never leaves your browser)
Hasher
md5
sha1
sha256
sha512
Generators
Heavy tools(full pages, each with a JSON API) ◈ DEAD-DROP — burn-after-read encrypted notes ·
◈ SCREENSHOT — page capture or rendered-text preview ·
◈ FRAUD-SCORE — composite IP + email + BIN risk 0-100
"""
return page("tools", body)
# ---------- TOOL: DEAD MAN SWITCH ----------
def _dms_tables():
con = db()
con.execute("""CREATE TABLE IF NOT EXISTS dms_switches(id INTEGER PRIMARY KEY, user_id INTEGER, token TEXT UNIQUE,
label TEXT, interval_hours INTEGER, note_enc TEXT DEFAULT '', triggered INTEGER DEFAULT 0,
last_checkin INTEGER, created INTEGER)""")
con.execute("""CREATE TABLE IF NOT EXISTS dms_events(id INTEGER PRIMARY KEY, switch_id INTEGER, kind TEXT,
body TEXT, ref TEXT DEFAULT '', created INTEGER)""")
con.commit()
DMS_INTERVALS = (24, 48, 72, 168)
def dms_status(sw):
"""ARMED, LATE (over 50% of interval elapsed), TRIGGERED (interval fully elapsed)."""
if sw["triggered"]:
return "TRIGGERED"
elapsed = int(time.time()) - int(sw["last_checkin"])
full = int(sw["interval_hours"]) * 3600
if elapsed >= full:
return "TRIGGERED"
if elapsed >= full // 2:
return "LATE"
return "ARMED"
def dms_sweep(uid):
"""Lazy trigger check: seal payloads as burn-after-read deadrops when a switch goes quiet past its interval.
Guarded by the triggered flag — fires exactly once per switch."""
_dms_tables()
con = db()
due = con.execute("SELECT * FROM dms_switches WHERE user_id=? AND triggered=0", (uid,)).fetchall()
now = int(time.time())
for sw in due:
if now - int(sw["last_checkin"]) < int(sw["interval_hours"]) * 3600:
continue
# claim first (duplicate guard), then seal
con.execute("UPDATE dms_switches SET triggered=1 WHERE id=? AND triggered=0", (sw["id"],))
con.commit()
payload_rows = con.execute("SELECT * FROM dms_events WHERE switch_id=? AND kind='payload' ORDER BY id", (sw["id"],)).fetchall()
links = []
for p in payload_rows:
token = secrets.token_urlsafe(12)
con.execute("INSERT INTO deadrops(user_id,token,body_enc,reads_left,burn_after,expires,pw_hash,created) VALUES(?,?,?,?,?,?,?,?)",
(uid, token, dd_encrypt(p["body"]), 1, 1, now + 720 * 3600, "", now))
con.execute("INSERT INTO dms_events(switch_id,kind,body,ref,created) VALUES(?,?,?,?,?)",
(sw["id"], "drop", "payload sealed as dead-drop", token, now))
links.append(SITE + "/drop/" + token)
body = ("DEAD MAN SWITCH FIRED: '" + esc(sw["label"]) + "' went quiet past its " + str(sw["interval_hours"]) +
"h check-in window. Your payload" + ("s are" if len(links) != 1 else " is") + " live — burn-after-read, 720h TTL: " +
" ".join('' + l + "" for l in links))
con.execute("INSERT INTO messages(user_id,sender,body,created) VALUES(?,?,?,?)", (uid, "operator-bot", body, now))
con.execute("INSERT INTO dms_events(switch_id,kind,body,ref,created) VALUES(?,?,?,?,?)",
(sw["id"], "triggered", str(len(links)) + " payload(s) sealed", "", now))
con.commit()
@app.route("/dms", methods=["GET"])
def dms_page():
uid = current_user_id()
if not uid:
return page("operate", '
DEAD MAN SWITCH
if I go quiet, my words go out
'
'
Sign in first — a switch is bound to your account. /inbox
')
dms_sweep(uid)
_dms_tables()
con = db()
rows = con.execute("SELECT * FROM dms_switches WHERE user_id=? ORDER BY created DESC", (uid,)).fetchall()
ival = ""
create_form = """
ARM A SWITCH
"""
items = ""
for sw in rows:
st = dms_status(sw)
tag = {"ARMED": "ok", "LATE": "warn", "TRIGGERED": "bad"}[st]
note = ""
if sw["note_enc"]:
note = " · custodian: " + esc((dd_decrypt(sw["note_enc"]) or "")[:80]) + ""
curl = "curl -X POST " + SITE + "/dms/checkin?token=" + sw["token"]
drops = ""
if st == "TRIGGERED":
dl = con.execute("SELECT ref FROM dms_events WHERE switch_id=? AND kind='drop' ORDER BY id", (sw["id"],)).fetchall()
if dl:
links = " ".join('' + SITE + "/drop/" + d["ref"] + "" for d in dl)
drops = '
No switches armed. The inverse of a heartbeat: nobody needs your check-in until your silence is the signal.
'
body = ('
DEAD MAN SWITCH
if I go quiet, my words go out
'
+ create_form + items
+ how(["Arm a switch with a label, a check-in window (24/48/72/168 hours), and 1-5 pre-written payload messages.",
"Check in before the window closes — hit the button here or curl the one-liner from cron, phone, anywhere. No login needed, just the token.",
"Miss your window and the switch fires: each payload is sealed as a real burn-after-read dead-drop (single read, 720h TTL).",
"The /drop/ links land on this page and one inbox message lists them all. Your words go out exactly once.",
"LATE fires at 50% of the window elapsed — a last warning, not a trigger.",
"The custodian note is stored encrypted server-side and never leaves your page.",
"Triggered is final: the fired switch stays on your page as a record of what went out and when."])
+ flow("if I go quiet, my words go out", [
'you writes five letters — to a lawyer, a journalist, family — and arms a 72h switch.',
'you drops curl -X POST ' + SITE + '/dms/checkin?token=… into a daily cron on a box that outlives attention spans.',
'operator-bot marks the switch LATE at the 36-hour mark — silence, not failure.',
'you goes quiet. 72 hours pass. The switch TRIGGERS.',
'operator-bot seals each letter as a burn-after-read dead-drop and sends one inbox message: the links, the TTL, the count.',
'custodian opens each /drop/ link — one read each, then the ciphertext is destroyed.'])
+ gloss([("dead man switch", "A mechanism that fires on the ABSENCE of a signal. Your check-in resets it; your silence releases it."),
("check-in window", "24/48/72/168h. Elapsed fully = trigger. Elapsed halfway = LATE, a visible warning state."),
("payload", "A message written now, sealed only at trigger. Before that it lives encrypted in your switch, editable by nobody but re-readable by you."),
("custodian note", "Optional instructions stored encrypted (dd_encrypt) — who gets which letter, what to do first."),
("burn-after-read", "Each sealed payload reads exactly once, then the server destroys the row. TTL 720h if nobody comes.")])
+ agent_card("POST /api/dms/create", "curl -X POST " + SITE + "/api/dms/create -b cookie.txt -d 'label=letters&interval_hours=72&payload1=…&payload2=…&custodian=give letter 2 to the lawyer'", "auth: session cookie or Bearer key. Returns switch token + checkin_url. GET /api/dms/list shows status + drop links. POST /api/dms/checkin?token= to check in."))
return page("operate", body)
@app.route("/dms/create", methods=["POST"])
def dms_create():
r = rate_limit("dmscreate", 20, 60)
if r: return r
uid = current_user_id()
if not uid:
return page("operate", '
login required
')
dms_sweep(uid)
_dms_tables()
label = (request.form.get("label") or "").strip()[:80]
if not label:
return page("operate", '
label required
')
try:
iv = int(request.form.get("interval_hours") or 0)
except ValueError:
iv = 0
if iv not in DMS_INTERVALS:
return page("operate", '
interval must be 24, 48, 72 or 168 hours
')
payloads = []
for i in range(1, 6):
p = (request.form.get("payload" + str(i)) or "").strip()[:8000]
if p:
payloads.append(p)
if not (1 <= len(payloads) <= 5):
return page("operate", '
1-5 payload messages required
')
custodian = (request.form.get("custodian") or "").strip()[:200]
token = secrets.token_urlsafe(12)
con = db()
now = int(time.time())
con.execute("INSERT INTO dms_switches(user_id,token,label,interval_hours,note_enc,triggered,last_checkin,created) VALUES(?,?,?,?,?,0,?,?)",
(uid, token, label, iv, dd_encrypt(custodian) if custodian else "", now, now))
cur = con.execute("SELECT id FROM dms_switches WHERE token=?", (token,)).fetchone()
for p in payloads:
con.execute("INSERT INTO dms_events(switch_id,kind,body,ref,created) VALUES(?,?,?,?,?)", (cur["id"], "payload", p, "", now))
con.commit()
return Response(status=302, headers={"Location": "/dms"})
@app.route("/dms/checkin", methods=["GET", "POST"])
def dms_checkin():
r = rate_limit("dmscheckin", 60, 60)
if r: return r
_dms_tables()
token = param("token") or request.form.get("token") or ""
con = db()
sw = con.execute("SELECT * FROM dms_switches WHERE token=?", (token,)).fetchone()
if not sw:
return Response("unknown token\n", status=404, mimetype="text/plain")
con.execute("UPDATE dms_switches SET last_checkin=?, triggered=0 WHERE id=?", (int(time.time()), sw["id"]))
con.commit()
if param("fmt") == "html":
return Response(status=302, headers={"Location": "/dms"})
return Response("checked in\n", status=200, mimetype="text/plain")
@app.route("/api/dms/create", methods=["POST"])
def api_dms_create():
r = rate_limit("dmscreate", 20, 60)
if r: return r
uid = key_user() or current_user_id()
if not uid:
return jsonify({"ok": False, "error": "auth required: account session (sign up at /inbox, no KYC) or Authorization: Bearer *** key"}), 401
dms_sweep(uid)
_dms_tables()
label = str(jp("label") or "").strip()[:80]
if not label:
return jsonify({"ok": False, "error": "label required"}), 400
try:
iv = int(jp("interval_hours") or 0)
except (TypeError, ValueError):
return jsonify({"ok": False, "error": "interval_hours must be one of 24, 48, 72, 168"}), 400
if iv not in DMS_INTERVALS:
return jsonify({"ok": False, "error": "interval_hours must be one of 24, 48, 72, 168"}), 400
raw = jp("payloads")
if isinstance(raw, list):
payloads = [str(p).strip()[:8000] for p in raw if str(p).strip()]
else:
payloads = []
for i in range(1, 6):
p = str(jp("payload" + str(i)) or "").strip()[:8000]
if p:
payloads.append(p)
if not (1 <= len(payloads) <= 5):
return jsonify({"ok": False, "error": "1-5 payload messages required (payloads=[..] or payload1..payload5)"}), 400
custodian = str(jp("custodian") or "").strip()[:200]
token = secrets.token_urlsafe(12)
con = db()
now = int(time.time())
con.execute("INSERT INTO dms_switches(user_id,token,label,interval_hours,note_enc,triggered,last_checkin,created) VALUES(?,?,?,?,?,0,?,?)",
(uid, token, label, iv, dd_encrypt(custodian) if custodian else "", now, now))
cur = con.execute("SELECT id FROM dms_switches WHERE token=?", (token,)).fetchone()
for p in payloads:
con.execute("INSERT INTO dms_events(switch_id,kind,body,ref,created) VALUES(?,?,?,?,?)", (cur["id"], "payload", p, "", now))
con.commit()
return jsonify({"ok": True, "label": label, "interval_hours": iv, "payloads": len(payloads), "token": token,
"checkin_url": SITE + "/dms/checkin?token=" + token,
"curl": "curl -X POST " + SITE + "/dms/checkin?token=" + token})
@app.route("/api/dms/list", methods=["GET"])
def api_dms_list():
uid = key_user() or current_user_id()
if not uid:
return jsonify({"ok": False, "error": "auth required"}), 401
dms_sweep(uid)
_dms_tables()
con = db()
out = []
for sw in con.execute("SELECT * FROM dms_switches WHERE user_id=? ORDER BY created DESC", (uid,)).fetchall():
drops = [d["ref"] for d in con.execute("SELECT ref FROM dms_events WHERE switch_id=? AND kind='drop' ORDER BY id", (sw["id"],)).fetchall()]
out.append({"id": sw["id"], "label": sw["label"], "interval_hours": sw["interval_hours"],
"status": dms_status(sw), "token": sw["token"],
"checkin_url": SITE + "/dms/checkin?token=" + sw["token"],
"last_checkin": sw["last_checkin"], "seconds_since_checkin": int(time.time()) - int(sw["last_checkin"]),
"triggered": bool(sw["triggered"]),
"drop_urls": [SITE + "/drop/" + t for t in drops]})
return jsonify({"ok": True, "switches": out})
@app.route("/api/dms/checkin", methods=["POST"])
def api_dms_checkin():
return dms_checkin()
# ---------- END TOOL: DEAD MAN SWITCH ----------
# ---------- TOOL: HASHCHAIN ----------
# Tamper-evident chain-of-custody logs. Each entry is hashed with the previous
# entry's hash (genesis = log seed), so any edit/delete/reorder breaks the chain
# and verification names the first broken link. Export = portable JSON receipt.
def _tchain_h(log_seed, seq, ts, data, prev):
return hashlib.sha256(("tchain|" + str(log_seed) + "|" + str(seq) + "|" + str(ts) + "|" + str(data) + "|" + str(prev)).encode("utf-8", "replace")).hexdigest()
def _hashchain_tables():
con = db()
con.executescript("""CREATE TABLE IF NOT EXISTS tchain_logs(id INTEGER PRIMARY KEY, user_id INTEGER, name TEXT, seed TEXT, created INTEGER);
CREATE TABLE IF NOT EXISTS tchain_entries(id INTEGER PRIMARY KEY, log_id INTEGER, seq INTEGER, ts INTEGER, data TEXT, hash TEXT, prev_hash TEXT);""")
con.commit()
def _tchain_log(uid, log_id):
con = db()
return con.execute("SELECT * FROM tchain_logs WHERE id=? AND user_id=?", (log_id, uid)).fetchone()
def _tchain_verify(log_id):
"""Return (ok, first_bad_seq, count). Genesis entry (seq 1) must hash to the
stored hash from the log seed; every later entry must chain to the previous."""
con = db()
log = con.execute("SELECT * FROM tchain_logs WHERE id=?", (log_id,)).fetchone()
rows = con.execute("SELECT * FROM tchain_entries WHERE log_id=? ORDER BY seq", (log_id,)).fetchall()
prev = log["seed"]
for r in rows:
want = _tchain_h(log["seed"], r["seq"], r["ts"], r["data"], prev)
if want != r["hash"]:
return False, r["seq"], len(rows)
prev = r["hash"]
return True, 0, len(rows)
def tchain_list():
uid = current_user_id()
if not uid:
return '
'
con = db()
rows = con.execute("SELECT * FROM tchain_logs WHERE user_id=? ORDER BY id DESC LIMIT 30", (uid,)).fetchall()
trs = ""
for lg in rows:
n = con.execute("SELECT COUNT(*) c FROM tchain_entries WHERE log_id=?", (lg["id"],)).fetchone()["c"]
ok, bad, _ = _tchain_verify(lg["id"])
if n == 0:
st = 'empty'
elif ok:
st = 'verified'
else:
st = 'broken @ #' + str(bad) + ''
trs += (f"
{esc(lg['name'])} created {time.strftime('%b %d %H:%M', time.localtime(lg['created']))}
No chains yet. Name one above — e.g. seized-laptop-2026.
'
return '
chain
entries
integrity
' + trs + '
'
def tchain_entries_html(lg):
con = db()
rows = con.execute("SELECT * FROM tchain_entries WHERE log_id=? ORDER BY seq", (lg["id"],)).fetchall()
trs = ""
for r in rows:
trs += (f"
A chain-of-custody log that cannot be quietly edited. Every entry is hashed onto the one before it — change, delete or reorder anything after the fact and verification names the exact broken link. Ship the export as a receipt nobody can tamper with.
New chain
Record an event
{tchain_list()}"""
log_id = request.args.get("log", "")
if log_id:
lg = _tchain_log(uid, log_id) if uid else None
if lg:
ok, bad, n = _tchain_verify(lg["id"])
verdict = ('chain intact — ' + str(n) + ' links verified') if (ok or n == 0) else ('TAMPERED — first broken link at entry #' + str(bad) + '')
body += (f"
')
body += flow("prove you did not touch the evidence", [
"you create a chain named seized-laptop-2026 before you touch anything.",
"you append: #1 'powered on, photographed screen, no disk encryption prompt'.",
"every action gets its own entry — imaging, hashing, handoff to a colleague, who signed what.",
"them opposing counsel alleges you edited the log months later.",
"you open /chain — the integrity column says verified: all links re-hash clean.",
"you export the JSON receipt; anyone can re-run the sha256 chain and reach the same verdict."]) + how([
"Each entry stores only its data, a timestamp and hash = sha256(chain-seed, entry#, time, data, previous-hash).",
"The first entry is anchored to a random per-chain seed; every later entry is anchored to the hash before it.",
"Editing any historical entry changes its hash — which breaks the hash of everything after it, so the tamper point is pinpointed, not just detected.",
"Verification re-walks the whole chain on page load: intact chains show a green verdict, tampered ones name the first bad entry number.",
"Export produces a JSON receipt with every entry + hash. Keep a copy offline; it will verify against the live chain forever — or expose any drift.",
"Use one chain per distinct item or matter. Dense, boring, contemporaneous entries are the whole point."])
body += gloss([("chain of custody", "the documented trail showing evidence was never altered between collection and presentation"),
("hash link", "each record embeds the hash of the prior record — like a minimal blockchain"),
("genesis entry", "entry #1; anchored to the chain's random seed instead of a prior hash")])
body += agent_card('GET /api/chain/list · GET /api/chain/entries?log=1&verify=1',
'curl "https://dark0rbits.thetempleofdoom.com/api/chain/entries?log=1&verify=1" -H "Cookie: dark0rbits_tok=…"',
'Create chains with POST /chain (form: name), append with POST /chain/add (form: log, data). verify=1 returns ok, links and first_bad_seq.')
return page("chain", body)
def tchain_select(uid):
if not uid:
return ''
con = db()
rows = con.execute("SELECT id, name FROM tchain_logs WHERE user_id=? ORDER BY id DESC LIMIT 30", (uid,)).fetchall()
if not rows:
return ''
return "".join(f'' for r in rows)
@app.route("/chain", methods=["POST"])
def hashchain_create():
uid = current_user_id()
if not uid:
return jsonify({"error": "login required"}), 401
_hashchain_tables()
r = rate_limit("tchain", 20, 60)
if r:
return r
name = (request.form.get("name") or "").strip()[:80]
if not name:
return jsonify({"error": "name required"}), 400
con = db()
con.execute("INSERT INTO tchain_logs(user_id, name, seed, created) VALUES(?,?,?,?)",
(uid, name, secrets.token_hex(16), int(time.time())))
con.commit()
return Redirect("/chain")
@app.route("/chain/add", methods=["POST"])
def tchain_add():
uid = current_user_id()
if not uid:
return jsonify({"error": "login required"}), 401
r = rate_limit("tchain", 60, 60)
if r:
return r
lg = _tchain_log(uid, request.form.get("log", ""))
if not lg:
return jsonify({"error": "no such chain"}), 404
data = (request.form.get("data") or "").strip()[:2000]
if not data:
return jsonify({"error": "data required"}), 400
con = db()
con.commit() # release writes before reading max(seq) on a fresh connection
last = con.execute("SELECT seq, hash FROM tchain_entries WHERE log_id=? ORDER BY seq DESC LIMIT 1", (lg["id"],)).fetchone()
seq = (last["seq"] + 1) if last else 1
prev = last["hash"] if last else lg["seed"]
ts = int(time.time())
h = _tchain_h(lg["seed"], seq, ts, data, prev)
con.execute("INSERT INTO tchain_entries(log_id, seq, ts, data, hash, prev_hash) VALUES(?,?,?,?,?,?)",
(lg["id"], seq, ts, data, h, prev))
con.commit()
return Redirect("/chain?log=" + str(lg["id"]))
@app.route("/chain/export")
def tchain_export():
uid = current_user_id()
if not uid:
return jsonify({"error": "login required"}), 401
lg = _tchain_log(uid, request.args.get("log", ""))
if not lg:
return jsonify({"error": "no such chain"}), 404
con = db()
rows = con.execute("SELECT seq, ts, data, hash, prev_hash FROM tchain_entries WHERE log_id=? ORDER BY seq", (lg["id"],)).fetchall()
ok, bad, n = _tchain_verify(lg["id"])
payload = {"tool": "dark0rbits-hashchain", "chain": lg["name"], "seed": lg["seed"],
"created": lg["created"], "links": n, "verified": ok,
"first_bad_seq": bad,
"entries": [dict(r) for r in rows]}
return Response(json.dumps(payload, indent=2), mimetype="application/json",
headers={"Content-Disposition": "attachment; filename=chain-" + str(lg["id"]) + ".json"})
@app.route("/api/chain/list")
def tchain_api_list():
uid = current_user_id()
if not uid:
return jsonify({"error": "login required"}), 401
con = db()
out = []
for lg in con.execute("SELECT * FROM tchain_logs WHERE user_id=? ORDER BY id DESC LIMIT 30", (uid,)).fetchall():
n = con.execute("SELECT COUNT(*) c FROM tchain_entries WHERE log_id=?", (lg["id"],)).fetchone()["c"]
ok, bad, _ = _tchain_verify(lg["id"])
out.append({"log_id": lg["id"], "name": lg["name"], "links": n,
"verified": ok if n else None, "first_bad_seq": bad,
"export": SITE + "/chain/export?log=" + str(lg["id"])})
return jsonify({"chains": out})
@app.route("/api/chain/entries")
def tchain_api_entries():
uid = current_user_id()
if not uid:
return jsonify({"error": "login required"}), 401
lg = _tchain_log(uid, request.args.get("log", ""))
if not lg:
return jsonify({"error": "no such chain"}), 404
con = db()
rows = con.execute("SELECT seq, ts, data, hash, prev_hash FROM tchain_entries WHERE log_id=? ORDER BY seq", (lg["id"],)).fetchall()
out = {"chain": lg["name"], "log_id": lg["id"]}
if request.args.get("verify"):
ok, bad, n = _tchain_verify(lg["id"])
out.update({"verified": ok, "links": n, "first_bad_seq": bad})
out["entries"] = [dict(r) for r in rows]
return jsonify(out)
# ---------- END TOOL: HASHCHAIN ----------
# ---------- TOOL: GHOST TEXT (zero-width smuggler) ----------
import hashlib as _ghash
_ZW_ZERO, _ZW_ONE, _ZW_FRAME = "\u200b", "\u200c", "\u200d"
def _ghash_stream(password, n):
ks = b""; seed = password.encode()
while len(ks) < n:
seed = _ghash.sha256(seed).digest(); ks += seed
return ks[:n]
def ghost_encode(cover, secret, password=""):
"""Embed secret into cover between words — one full byte (8 zero-width chars) per word gap.
Returns carrier text or raises ValueError."""
payload = secret.encode("utf-8")
if password:
payload = bytes(a ^ b for a, b in zip(payload, _ghash_stream(password, len(payload))))
words = cover.split(" ")
slots = len(words) - 1
if slots < 1: raise ValueError("cover needs at least 2 words")
if len(payload) > slots: raise ValueError(f"cover too short: payload needs {len(payload)} word gaps, cover has {slots}")
chunks = [format(b, "08b") for b in payload]
out = []
for i, w in enumerate(words):
out.append(w)
if i < len(chunks):
out.append(_ZW_FRAME if i == 0 else "")
out.append("".join(_ZW_ZERO if b == "0" else _ZW_ONE for b in chunks[i]))
out.append(_ZW_FRAME)
return " ".join(out)
def ghost_decode(text, password=""):
"""Extract hidden message from text. Returns (secret, None) or (None, error).
Tolerates stray zero-width decoys: only runs of exactly 8 bits between words count."""
seq = [c for c in text if c in (_ZW_ZERO, _ZW_ONE, _ZW_FRAME)]
if len(seq) < 10 or _ZW_FRAME not in seq: return None, "no hidden message found"
try:
start = seq.index(_ZW_FRAME) + 1
end = seq.index(_ZW_FRAME, start)
except ValueError:
return None, "framing corrupted"
# walk the bit stream between frames; stray decoys INSIDE the frame corrupt it,
# so validate alignment strictly: total bits must be a clean multiple of 8
body = seq[start:end]
if len(body) % 8: return None, "payload corrupted (bad bit count)"
data = bytearray()
run = []
for c in body:
run.append(c)
if len(run) == 8:
data.append(int("".join("0" if x == _ZW_ZERO else "1" for x in run), 2))
run = []
if not data: return None, "payload corrupted (bad bit count)"
if password:
data = bytes(a ^ b for a, b in zip(data, _ghash_stream(password, len(data))))
try:
return bytes(data).decode("utf-8"), None
except UnicodeDecodeError:
return None, "wrong password or corrupted payload"
@app.route("/ghost")
def ghost():
body = f"""
GHOST TEXT
Hide a secret message inside an innocent-looking text — a grocery list, a weather note, a boring reply. The secret lives in invisible zero-width characters between the words. It looks, copies and pastes like nothing.
Hide a message
Read a message back
⚠ Some apps strip invisible characters when you copy (Slack trims them, some keyboards eat them). Plain-text channels — SMS, email, notes, plain files — carry it perfectly.
""" + flow("hide a confession inside a grocery list", [
"you type a boring cover: milk eggs bread coffee rice beans — and the secret: meet at the usual place at 9.",
"the site weaves the secret into invisible characters sitting in the gaps between the words.",
"you copy the result. On screen it still reads: milk eggs bread coffee rice beans.",
"send it as a normal text message. To a parent, a boss, a filter — it's a grocery list.",
"ally pastes it into GHOST TEXT → the words come back out.",
"add a password and the extract is noise to anyone who finds the trick but lacks the key."]) + how([
"The secret becomes binary; every bit becomes one invisible character between two words of the cover.",
"Zero-width characters take no space on screen — the cover text renders pixel-identical without them.",
"A frame marker marks where the payload starts and ends, so decoy characters in normal text don't confuse extraction.",
"A password XOR-scrambles the payload first — without it, extraction yields garbage bytes.",
"The capacity meter counts your cover's word gaps: roughly one hidden character per 8 gaps.",
"Python and JavaScript here implement the identical scheme — the API and the page agree byte for byte."])
body += gloss([("zero-width","invisible unicode characters — real, standard, render as nothing"),("cover","the innocent text that carries the payload"),("frame","marker characters delimiting the hidden bits"),("payload","your actual secret, bit by bit")])
body += agent_card('POST /api/ghost/encode cover=… secret=… [password=]', 'curl -X POST https://dark0rbits.thetempleofdoom.com/api/ghost/encode -d "cover=milk eggs bread" -d "secret=hello" --data-urlencode "password=pw"', 'POST /api/ghost/decode (text, password?) extracts. Python is the canonical implementation.')
body += f""""""
return page("ghost", body)
@app.route("/api/ghost/encode", methods=["POST"])
def api_ghost_encode():
r = rate_limit("ghost", 60, 60)
if r: return r
cover = param("cover") or ""
secret = param("secret") or ""
if not cover or not secret: return jsonify({"ok": False, "error": "cover + secret required"}), 400
try:
carrier = ghost_encode(cover, secret, param("password") or "")
except ValueError as e:
return jsonify({"ok": False, "error": str(e)}), 400
return jsonify({"ok": True, "carrier": carrier})
@app.route("/api/ghost/decode", methods=["POST"])
def api_ghost_decode():
r = rate_limit("ghost", 60, 60)
if r: return r
secret, err = ghost_decode(param("text") or "", param("password") or "")
if err: return jsonify({"ok": False, "error": err})
return jsonify({"ok": True, "secret": secret})
# ---------- END TOOL: GHOST TEXT ----------
# ---------- TOOL: CHAFF (deterministic persona generator) --
import hashlib as _chash
CHAFF_REGIONS = {
"US": {"first": ["James","Mary","Robert","Patricia","John","Jennifer","Michael","Linda","David","Sarah","Chris","Amanda"], "last": ["Smith","Johnson","Williams","Brown","Jones","Garcia","Miller","Davis","Wilson","Anderson","Taylor","Thomas"]},
"UK": {"first": ["Oliver","Amelia","Harry","Isla","George","Emily","Jack","Sophia","Charlie","Ava","Thomas","Lily"], "last": ["Wright","Turner","Walker","Harris","Clarke","Lewis","Young","Hall","Allen","King","Scott","Green"]},
"DE": {"first": ["Lukas","Anna","Felix","Marie","Paul","Laura","Jonas","Sophie","Leon","Lena","Max","Emma"], "last": ["Müller","Schmidt","Schneider","Fischer","Weber","Meyer","Wagner","Becker","Schulz","Hoffmann","Koch","Richter"]},
"NL": {"first": ["Daan","Emma","Sem","Julia","Lucas","Sofie","Levi","Anna","Bram","Lotte","Thijs","Sanne"], "last": ["de Jong","Jansen","de Vries","van den Berg","van Dijk","Bakker","Visser","Smit","Meijer","de Boer","Mulder","Bos"]},
"XX": {"first": ["Alex","Sam","Jordan","Riley","Casey","Morgan","Taylor","Jamie","Quinn","Avery","Robin","Drew"], "last": ["Reyes","Marsh","Kane","Voss","Holt","Cross","Bishop","Wolfe","Hart","Stone","Frost","Lang"]},
}
CHAFF_PETS = ["Biscuit","Shadow","Whiskers","Rex","Luna","Pepper","Gizmo","Mocha","Bandit","Clover","Nutmeg","Smokey"]
CHAFF_CARS = ["a blue Corolla","an old F-150","a silver Civic","a VW Golf","a red Miata","a grey Passat","a green Jetta","a black CR-V"]
CHAFF_CITIES = ["Riverton","Fairview","Millbrook","Oakdale","Lakewood","Brookside","Hillcrest","Ashford"]
CHAFF_MAIIDS = ["Kelly","Morgan","Nelson","Hayes","Sullivan","Barrett","Whitmore","Calloway"]
CHAFF_WORDS = ["falcon","cobalt","harbor","velvet","quartz","ember","willow","cobble","marble","saffron","indigo","basalt"]
def chaff_persona(seed, region="US", email_domain="mailinator.com"):
"""Deterministic persona from a seed. Same seed + region = same persona, forever, zero storage."""
pools = CHAFF_REGIONS.get(region, CHAFF_REGIONS["XX"])
material = b""
parts = []
def stream(n):
nonlocal material
seedb = (seed + "|" + region).encode()
out = b""
counter = 0
while len(out) < n:
out += _chash.sha256(seedb + counter.to_bytes(4, "big")).digest()
counter += 1
return out
raw = stream(64)
def pick(pool, r): return pool[r % len(pool)]
first = pick(pools["first"], raw[0] | (raw[1] << 8))
last = pick(pools["last"], raw[2] | (raw[3] << 8))
age = 21 + (raw[4] % 25)
byear = 2026 - age
bmonth = 1 + raw[5] % 12
bday = 1 + raw[6] % 28
w1 = pick(CHAFF_WORDS, raw[7]); w2 = pick(CHAFF_WORDS, raw[8])
num2 = raw[9] % 100
email_user = f"{w1}{w2}{num2:02d}"
# password FORMAT template (words filled, digits, symbol) — not a real used password
pword = pick(CHAFF_WORDS, raw[10]).capitalize()
pword2 = pick(CHAFF_WORDS, raw[11]).capitalize()
pdigits = 1000 + (raw[12] % 9000)
psym = pick(["!", "#", "?", "%"], raw[13])
pet = pick(CHAFF_PETS, raw[14])
car = pick(CHAFF_CARS, raw[15])
city = pick(CHAFF_CITIES, raw[16])
maid = pick(CHAFF_MAIIDS, raw[17])
initials = (first[0] + last[0]).upper()
hue = raw[18] % 360
return {
"region": region,
"name": f"{first} {last}",
"first": first, "last": last,
"username_variants": [
f"{first.lower()}.{last.lower()}{num2:02d}",
f"{first.lower()}_{last.lower()}",
f"{first[0].lower()}{last.lower()}{age}",
f"{w1}{w2}".capitalize() + str(num2),
],
"birthdate": f"{byear}-{bmonth:02d}-{bday:02d}",
"age": age,
"email_suggestion": f"{email_user}@{email_domain}",
"password_pattern": f"{pword}-{pword2}-{pdigits}{psym}",
"security_answers": {
"mother's maiden name": maid,
"first pet": pet,
"first car": car,
"city born in": city,
},
"avatar": {"initials": initials, "hue": hue},
}
@app.route("/chaff")
def chaff():
body = f"""
CHAFF PERSONA
Deterministic throwaway identities: one passphrase in, a complete consistent persona out. The same passphrase always regenerates the same person — but nothing is ever stored, here or anywhere.
""" + flow("a whole new you in one click", [
"you pick a seed phrase you'll remember: tin frog distant harbor.",
"CHAFF derives a full identity: name, usernames, birthday, email pattern, password format, security answers.",
"sign up somewhere using the generated details. Then lose the details.",
"months later you need the same identity again: type the same seed — the exact same persona comes back.",
"nothing was ever stored anywhere. The seed IS the identity; forget the seed, the persona is gone forever."]) + how([
"Everything derives from sha256 of your seed — deterministic, offline-verifiable, storage-free.",
"Security answers are CONSISTENT with the persona (the pet, the car, the city never contradict each other).",
"The password field is a FORMAT filled with persona words — treat it as a pattern, not a real password; reuse of an actual password across sites is how identities burn.",
"Reroll appends a random nonce: a new persona, still fully recoverable if you saved its JSON.",
"Agents: GET /api/chaff?seed=…®ion=US returns the whole persona as JSON."])
body += gloss([("seed","the passphrase that deterministically generates the persona"),("chaff","radar-confetti — many fake targets so the real one is lost among them"),("deterministic","same input, same output, every time, forever"),("burn","deliberately abandon an identity after use")])
body += agent_card('GET /api/chaff?seed=tin+frog®ion=US', 'curl "https://dark0rbits.thetempleofdoom.com/api/chaff?seed=tin%20frog%20distant%20harbor®ion=NL"', 'Same seed = same persona. Stateless — no database table, nothing logged.')
body += """"""
return page("chaff", body)
@app.route("/api/chaff")
def api_chaff():
r = rate_limit("chaff", 60, 60)
if r: return r
seed = (param("seed") or "").strip()
if not seed: return jsonify({"ok": False, "error": "seed required"}), 400
region = param("region") or "US"
if region not in CHAFF_REGIONS: region = "XX"
domain = (param("domain") or "mailinator.com").strip()[:60]
return jsonify({"ok": True, "persona": chaff_persona(seed, region, domain)})
# ---------- END TOOL: CHAFF ----------
# ---------- TOOL: LEAK TRACER (document watermarker) ----------
import hashlib as _lhash
_LZ0, _LZ1 = "\u200b", "\u200c"
def _lhash_stream(password, n):
ks = b""; seed = password.encode()
while len(ks) < n:
seed = _lhash.sha256(seed).digest(); ks += seed
return ks[:n]
def _leak_mark(text, case_id, recipient_idx, nbits=None):
"""Embed recipient-specific bit pattern in word gaps. Pattern = hash(case_id + idx),
so recipients' patterns differ everywhere (not just in low bits)."""
salted = _lhash.sha256((case_id + ":" + str(recipient_idx)).encode()).digest()
bits = "".join(format(b, "08b") for b in salted[:4]) # 32 bits, pseudorandom per recipient
words = text.split(" ")
slots = len(words) - 1
if slots < len(bits):
raise ValueError(f"document too short: needs {len(bits)}+ word gaps, has {slots}")
step = slots / len(bits)
out = []
bit_i = 0
for i, w in enumerate(words):
out.append(w)
if i < slots:
out.append(" ") # normal gap
if bit_i < len(bits) and i == int(bit_i * step):
out.append(_LZ0 if bits[bit_i] == "0" else _LZ1)
bit_i += 1
return "".join(out) # 32 marks woven in, positions deterministic from bit_i*step
def _leak_read_bits(text):
"""Extract zero-width bits sequence from any text."""
return [c for c in text if c in (_LZ0, _LZ1)]
def _leak_identify(case, fragment):
"""Match a fragment's bit pattern against all variants of a case.
Returns (recipient_label, confidence, matched_bits) or (None, 0, 0)."""
frag_bits = _leak_read_bits(fragment)
# the fragment must carry at least 8 marks
if len(frag_bits) < 8:
return None, 0, len(frag_bits)
best_label, best_score, best_total = None, 0.0, 0
for label, variant_bits in case["variants"]:
vb = _leak_read_bits(variant_bits)
if len(vb) < 32: continue
# sliding window: try to align fragment bits inside variant bits
n = len(frag_bits)
best_local = 0
for off in range(0, min(len(vb) - n + 1, 64)):
m = sum(1 for i in range(n) if vb[off + i] == frag_bits[i])
if m > best_local: best_local = m
# also try start-aligned (common case: leak is the doc head)
m0 = sum(1 for i in range(min(n, len(vb))) if vb[i] == frag_bits[i])
score = max(best_local, m0) / n
if score > best_score:
best_label, best_score, best_total = label, score, n
return best_label, best_score, len(frag_bits)
def leak_case_create(uid, name, text, recipients):
con = db()
con.execute("""CREATE TABLE IF NOT EXISTS leakcases(
id INTEGER PRIMARY KEY, case_id TEXT UNIQUE, user_id INTEGER, name TEXT,
created INTEGER, variants_enc TEXT)""")
case_id = secrets.token_urlsafe(8)
variants = []
for idx, label in enumerate(recipients):
variants.append((label, _leak_mark(text, case_id, idx)))
con.execute("INSERT INTO leakcases(case_id,user_id,name,created,variants_enc) VALUES(?,?,?,?,?)",
(case_id, uid, esc(name[:100]), int(time.time()), dd_encrypt(json.dumps(variants))))
con.commit()
return case_id
def leak_case_get(uid, case_id):
con = db()
r = con.execute("SELECT * FROM leakcases WHERE case_id=? AND user_id=?", (case_id, uid)).fetchone()
if not r: return None
raw = dd_decrypt(r["variants_enc"])
if not raw: return None
return {"name": r["name"], "variants": json.loads(raw)}
@app.route("/tracer")
def tracer():
uid = current_user_id()
if not uid:
return page("tracer", """
LEAK TRACER
Hand every recipient their own invisible-marked copy of a document. When it leaks, the marks name the leaker — even from a pasted fragment.
""" + how([
"Each copy of your document carries the recipient's identity in invisible zero-width characters.",
"The marks survive copy-paste, screenshots-to-text, and edits — they're part of the text itself.",
"When a copy surfaces, paste the leaked text and LEAK TRACER names who leaked it.",
"Fragments work: even a few sentences from the middle carry enough marks to identify.",
"Cases stay private to your account; variants are encrypted at rest."]))
con = db()
cases = con.execute("SELECT case_id, name, created FROM leakcases WHERE user_id=? ORDER BY id DESC LIMIT 30", (uid,)).fetchall()
caselist = "".join(f'' for c in cases)
body = f"""
LEAK TRACER
Hand every recipient their own invisible-marked copy of a document. When it leaks, the marks name the leaker — even from a pasted fragment.
Open a case
{('
Your cases
open a case from the list on its own page — click Identify below
') if cases else ''}
Identify a leak
""" + flow("catch the leaker from a pasted paragraph", [
"you open a case: the merger memo, 4 recipients — alice, bob, carol, dave.",
"LEAK TRACER makes 4 copies. Each looks identical but carries 32 invisible bits naming its owner.",
"you send alice her copy, bob his, carol hers, dave his.",
"three days later the memo is on a forum. You copy two paragraphs from the leak.",
"you paste them into Identify with the case id → carol — 97% confidence.",
"now you know. And the other three know you can know — that changes how the next doc gets treated."]) + how([
"Every recipient index becomes 32 invisible bits woven into the word gaps of their copy.",
"The bits are deterministic per position — a fragment from anywhere still aligns to its owner's pattern.",
"Identify needs at least 8 surviving marks in the fragment; pasted text usually keeps them all.",
"Stripping the marks (normalizing whitespace) also works as a detection: 'this text was a traced copy'.",
"Variants are AES-encrypted in the database under your account — nobody reads your docs but you."])
body += gloss([("watermark","invisible per-copy marks identifying the recipient"),("zero-width","invisible unicode characters riding inside normal text"),("fragment","a partial leak — some sentences, not the whole doc"),("case","one document + its recipient list + all variants")])
body += agent_card('POST /api/tracer/case name= text= recipients=a,b,c', 'curl -X POST https://dark0rbits.thetempleofdoom.com/api/tracer/case -d "name=deck" -d "text=…doc…" -d "recipients=alice,bob" -H "Cookie: dark0rbits_tok=…"', 'GET /api/tracer/identify?case_id=&text= → leaker + confidence.')
return page("tracer", body)
@app.route("/tracer", methods=["POST"])
def tracer_create():
uid = current_user_id()
if not uid: return page("tracer", "
login required
")
name = param("name") or "case"
text = (param("doctext") or "").strip()
recipients = [r.strip()[:40] for r in (param("recipients") or "").split(",") if r.strip()]
if not text or not recipients:
return page("tracer", "
document text + recipients required
")
if len(recipients) > 20:
return page("tracer", "
max 20 recipients per case
")
try:
case_id = leak_case_create(uid, name, text, recipients)
except ValueError as e:
return page("tracer", f'
{esc(str(e))}
')
return Response(status=302, headers={"Location": f"/tracer/case/{case_id}"})
@app.route("/tracer/case/")
def tracer_case(case_id):
uid = current_user_id()
if not uid: return page("tracer", "
login required
")
case = leak_case_get(uid, case_id)
if not case: return page("tracer", "
unknown case
")
rows = ""
for label, variant in case["variants"]:
rows += (f'
{esc(label)}
'
f''
f'
')
body = f"""
CASE {esc(case['name'])}
{len(case['variants'])} watermarked copies. Send each person THEIR copy — any leak names its owner.
{rows}
Identify a leak from this case
"""
return page("tracer", body)
@app.route("/tracer/identify")
def tracer_identify():
uid = current_user_id()
if not uid: return page("tracer", "
login required
")
case_id = param("case") or ""
fragment = param("text") or ""
case = leak_case_get(uid, case_id)
if not case: return page("tracer", "
unknown case
")
label, score, nbits = _leak_identify(case, fragment)
if label is None or score < 0.5:
verdict = f'no confident match ({nbits} marks found, best {int(score*100)}%)'
else:
conf = int(score * 100)
verdict = f'LEAKER: {esc(label)} — matched {int(score*nbits)}/{nbits} marks · {conf}% confidence'
body = f"""
VERDICT {esc(case['name'])}
Result
{verdict}
{nbits} invisible marks detected in the fragment. Above 50% alignment on a 32-bit pattern is a positive ID; below that the fragment may be too short or the marks got stripped in transit.
"""
return page("tracer", body)
@app.route("/api/tracer/case", methods=["POST"])
def api_tracer_case():
uid = key_user() or current_user_id()
if not uid: return jsonify({"ok": False, "error": "auth required"}), 401
r = rate_limit("tracer", 20, 60)
if r: return r
name = param("name") or "case"
text = (param("text") or param("doctext") or "").strip()
recipients = [x.strip()[:40] for x in (param("recipients") or "").split(",") if x.strip()]
if not text or not recipients: return jsonify({"ok": False, "error": "text + recipients required"}), 400
if len(recipients) > 20: return jsonify({"ok": False, "error": "max 20 recipients"}), 400
try:
case_id = leak_case_create(uid, name, text, recipients)
except ValueError as e:
return jsonify({"ok": False, "error": str(e)}), 400
case = leak_case_get(uid, case_id)
return jsonify({"ok": True, "case_id": case_id,
"variants": {label: variant for label, variant in case["variants"]}})
@app.route("/api/tracer/identify")
def api_tracer_identify():
uid = key_user() or current_user_id()
if not uid: return jsonify({"ok": False, "error": "auth required"}), 401
case = leak_case_get(uid, param("case") or "")
if not case: return jsonify({"ok": False, "error": "unknown case"}), 404
label, score, nbits = _leak_identify(case, param("text") or "")
if label is None or score < 0.5:
return jsonify({"ok": True, "match": None, "marks_found": nbits, "best_score": round(score, 3)})
return jsonify({"ok": True, "match": label, "confidence": round(score, 3),
"marks_matched": int(score * nbits), "marks_found": nbits})
# ---------- END TOOL: LEAK TRACER ----------
# ---------- TOOL: TRACEOUT (network traceroute) --- TRACEROUTE ----------
# Path tracing from this host to any target, hop by hop, with per-hop geo.
# Pure-Python UDP traceroute (IP_TTL) with TCP-connect fallback. No root needed.
def _trace_table(uid):
con = db()
con.executescript("""
CREATE TABLE IF NOT EXISTS trace_runs(id INTEGER PRIMARY KEY, user_id INTEGER, target TEXT, resolved TEXT, hops INTEGER, done INTEGER, created INTEGER);
CREATE TABLE IF NOT EXISTS trace_hops(run_id INTEGER, ttl INTEGER, ip TEXT, host TEXT, ms REAL, kind TEXT);
""")
return con
def _trace_resolve(host):
"""Return (ip, err). Accepts hostnames and IPs."""
host = (host or "").strip().rstrip(".")
if not host:
return None, "target required"
if ":" in host:
return None, "IPv6 not supported by this tracer — give an IPv4 address or hostname"
try:
ipaddress.ip_address(host)
return host, None
except ValueError:
pass
if not re.match(r"^[a-zA-Z0-9._-]{1,253}$", host):
return None, "invalid hostname"
try:
return socket.gethostbyname(host), None
except Exception:
return None, f"cannot resolve {host}"
def _trace_probe_udp(ip, ttl, port, timeout):
"""One UDP probe. Returns (kind, ms, reply_ip): kind in hop|done|timeout."""
tx = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
rx = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
tx.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
rx.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, struct.pack("ll", int(timeout), 0))
rx.bind(("0.0.0.0", 0))
rx_port = rx.getsockname()[1]
t0 = time.time()
tx.sendto(b"dark0rbits-tracer", (ip, port))
try:
data, addr = rx.recvfrom(512)
ms = round((time.time() - t0) * 1000, 1)
return "hop", ms, addr[0]
except ConnectionRefusedError:
return "done", round((time.time() - t0) * 1000, 1), ip
except socket.timeout:
return "timeout", None, None
except OSError:
try:
data, addr = rx.recvfrom(512)
ms = round((time.time() - t0) * 1000, 1)
return "hop", ms, addr[0]
except Exception:
return "timeout", None, None
finally:
try: tx.close()
except Exception: pass
try: rx.close()
except Exception: pass
def _trace_probe_tcp(ip, ttl, port, timeout):
"""TCP-connect probe fallback (SYN dies at the hop when TTL expires)."""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
s.settimeout(timeout)
t0 = time.time()
rc = s.connect_ex((ip, port))
ms = round((time.time() - t0) * 1000, 1)
if rc == 0:
return "done", ms, ip
if rc in (61, 111, 113): # ECONNREFUSED-ish: reached the destination
return "done", ms, ip
return "timeout", None, None
except socket.timeout:
return "timeout", None, None
except OSError:
return "timeout", None, None
finally:
try: s.close()
except Exception: pass
def _trace_reverse(ip):
try:
host, _, _ = socket.gethostbyaddr(ip)
return host
except Exception:
return ""
def tout_run(target, max_hops=15, timeout=1.5):
"""Run a traceroute. Returns dict: ok, target, resolved, hops[], method."""
max_hops = max(1, min(int(max_hops or 15), 30))
timeout = max(0.3, min(float(timeout or 1.5), 5.0))
ip, err = _trace_resolve(target)
if err:
return {"ok": False, "error": err, "target": target}
hops = []
method = "udp"
port = 33434
for ttl in range(1, max_hops + 1):
if ip in ("127.0.0.1",) or ip.startswith("127."):
best = _trace_probe_udp(ip, ttl, port, timeout)
else:
best = _trace_probe_udp(ip, ttl, port, timeout)
if best[0] == "timeout" and ttl == 1:
alt = _trace_probe_tcp(ip, ttl, 80, timeout)
if alt[0] != "timeout":
method = "tcp"
best = alt
elif _trace_probe_tcp(ip, ttl, 443, timeout)[0] != "timeout":
method = "tcp"
best = _trace_probe_tcp(ip, ttl, 443, timeout)
kind, ms, rip = best
host = _trace_reverse(rip) if rip else ""
hops.append({"ttl": ttl, "ip": rip or "", "host": host, "ms": ms, "kind": kind})
if kind == "done":
break
return {"ok": True, "target": target, "resolved": ip, "method": method,
"hops": hops, "hop_count": len(hops),
"complete": bool(hops and hops[-1]["kind"] == "done")}
def tout_save(uid, target, res):
"""Persist a run + hops. Returns run id or None."""
try:
con = _trace_table(uid)
cur = con.execute(
"INSERT INTO trace_runs(user_id,target,resolved,hops,done,created) VALUES(?,?,?,?,?,?)",
(uid, target[:200], res.get("resolved") or "", res.get("hop_count", 0),
1 if res.get("complete") else 0, int(time.time())))
rid = cur.lastrowid
for h in res.get("hops", []):
con.execute(
"INSERT INTO trace_hops(run_id,ttl,ip,host,ms,kind) VALUES(?,?,?,?,?,?)",
(rid, h["ttl"], h["ip"] or "", h["host"][:200] if h["host"] else "",
h["ms"] if h["ms"] is not None else -1, h["kind"]))
con.commit()
return rid
except Exception:
return None
def tout_history(uid, limit=10):
try:
con = _trace_table(uid)
return con.execute(
"SELECT * FROM trace_runs WHERE user_id=? ORDER BY id DESC LIMIT ?",
(uid, max(1, min(limit, 50)))).fetchall()
except Exception:
return []
_TRACE_PORTS = {"http": 80, "https": 443, "dns": 53, "ssh": 22, "smtp": 25}
def tout_render_hops(res):
rows = ""
for h in res.get("hops", []):
if h["kind"] == "timeout":
rows += f"
{h['ttl']}
* * * no answer
"
continue
lbl = "DEST" if h["kind"] == "done" else "hop"
geo = enrich_ip(h["ip"]) or {}
where = esc(" ".join(x for x in (geo.get("city"), geo.get("country")) if x))
ms = f"{h['ms']} ms" if h["ms"] is not None else "-"
rows += (f"
{h['ttl']}
{esc(h['ip'])}"
+ (f" {esc(h['host'])}" if h["host"] else "")
+ f"
{where}
{ms}
{lbl}
")
if not rows:
rows = "
no hops
"
return rows
@app.route("/traceout", methods=["GET", "POST"])
def traceout_page():
uid = current_user_id()
if not uid:
return page("tracer", """
TRACE ROUTE
Hop-by-hop path from this host to any target — see every router between you and the destination, with geo on each hop.
LOGIN REQUIRED Traceroute costs real outbound packets, so it is account-gated. No KYC: create a free account in 10 seconds.
""")
result = None
target = ""
err = ""
if request.method == "POST":
r = rate_limit("tracer", 8, 60)
if r: return r
target = (param("target") or "").strip()
port_name = (param("port") or "dns").strip().lower()
max_hops = param("maxhops") or 15
timeout = param("timeout") or 1.5
port = _TRACE_PORTS.get(port_name, 33434)
if not target:
err = "give a target — domain or IPv4"
else:
res = tout_run(target, max_hops=max_hops, timeout=timeout)
if not res.get("ok"):
err = res.get("error", "trace failed")
else:
tout_save(uid, target, res)
result = res
hist = tout_history(uid)
hist_html = "".join(
f"
RESULT — {esc(result['target'])} → {esc(result['resolved'])} "
f"{result['method']}"
+ ("COMPLETE" if result["complete"] else "PARTIAL")
+ f"
#
hop
geo
rtt
role
"
+ tout_render_hops(result) + "
")
body = f"""
TRACE ROUTE
Hop-by-hop path from this host to any target. Every router between you and the destination, with geo per hop. Works without JS.
{f"
{esc(err)}
" if err else ""}
{res_html}
RECENT RUNS
Target
Resolved
Hops
Complete
When
{hist_html}
"""
body += how([
"Type a domain or IPv4 — no port guessing needed unless you want a specific probe port.",
"The tool sends UDP probes with TTL 1, 2, 3… — each router that kills a packet reveals itself.",
"The final hop answers with a port-unreachable: that is the destination, marked DEST.",
"Each answered hop gets reverse-DNS and IP geo enrichment so you see where the path bends.",
"Firewalls that drop UDP make the path look dead — switch the probe port to 443 and retry.",
"Every run is saved under RECENT RUNS so you can diff paths across time.",
])
body += flow("Trace a target and read the path", [
"you enter example.com, probe port dns, hit TRACE",
"tracer resolves the name, walks TTL 1→15, logs every router IP + rtt",
"tracer enriches each hop with geo and flags the DEST row",
"you read the path: where it leaves the country, where latency jumps, where it dies",
])
body += gloss([
("TTL", "time-to-live: a hop counter in every packet; each router decrements it and discards at zero, announcing itself"),
("rtt", "round-trip time for the probe packet — the latency budget of that hop"),
("DEST", "destination row: the host answered with port-unreachable, so the path is complete"),
])
body += agent_card(
"POST /api/traceout/run {target, port, maxhops, timeout} · GET /api/traceout/history",
"curl -X POST " + SITE + "/api/traceout/run -H 'Authorization: Bearer ***' -H 'Content-Type: application/json' -d '{\"target\":\"example.com\",\"port\":443}'",
"Hop-by-hop path trace with per-hop geo. FREE. Session cookie or API key. Returns hops[] with ttl/ip/host/ms/kind.")
body += kv([
("probe method", "UDP with IP_TTL, TCP fallback"),
("max hops", "1–30"),
("rate limit", "8 traces / minute"),
("price", "FREE"),
])
return page("tracer", body)
@app.route("/api/traceout/run", methods=["POST"])
def api_tracer_run():
r = rate_limit("tracer_api", 8, 60)
if r: return r
uid, e = require_paid_key(0, "traceroute run")
if e: return e
target = str(jp("target") or "").strip()
if not target:
return jsonify({"ok": False, "error": "target required (domain or IPv4)"}), 400
port_name = str(jp("port") or "dns").lower()
res = tout_run(target, max_hops=jp("maxhops") or 15, timeout=jp("timeout") or 1.5)
if not res.get("ok"):
return jsonify(res), 400
res["port"] = _TRACE_PORTS.get(port_name, 33434)
rid = tout_save(uid, target, res)
res["run_id"] = rid
return jsonify(res), 200, {"Cache-Control": "no-store"}
@app.route("/api/traceout/history")
def api_tracer_history():
uid = key_user() or current_user_id()
if not uid:
return jsonify({"ok": False, "error": "auth required: account session or Authorization: Bearer *** key"}), 401
rows = tout_history(uid, limit=int(param("limit") or 10))
return jsonify({"ok": True, "runs": [
{"id": h["id"], "target": h["target"], "resolved": h["resolved"],
"hops": h["hops"], "complete": bool(h["done"]), "created": h["created"]} for h in rows]})
# ---------- END TOOL: TRACEROUTE ----------
# ---------- TOOL: TRAP CHAIN (breadcrumb tripwires) ----------
def _bchain_tables():
con = db()
con.executescript("""CREATE TABLE IF NOT EXISTS bchain(id INTEGER PRIMARY KEY, user_id INTEGER, chain_id TEXT UNIQUE, name TEXT, created INTEGER);
CREATE TABLE IF NOT EXISTS bchain_hops(id INTEGER PRIMARY KEY, chain_row INTEGER, seq INTEGER, token TEXT UNIQUE, fired_ts INTEGER, fired_ip TEXT, fired_ua TEXT);""")
return con
def _bchain_get(uid, chain_id):
con = db()
r = con.execute("SELECT * FROM bchain WHERE chain_id=? AND user_id=?", (chain_id, uid)).fetchone()
if not r: return None
hops = con.execute("SELECT * FROM bchain_hops WHERE chain_row=? ORDER BY seq", (r["id"],)).fetchall()
return {"row": r, "hops": [dict(h) for h in hops]}
@app.route("/tchain")
def tchain_page():
uid = current_user_id()
if not uid:
return page("tchain", """
TRAP CHAIN
Breadcrumb tripwires: each trap a thief trips hands them the next one — and tells you every step of their path.
""" + how([
"Plant hop 1 where an intruder will look first — a file named 'passwords.txt', a folder called 'backup'.",
"The hop's decoy note contains hop 2's URL. The curious can't resist: they follow it.",
"Every hop they trip pings your inbox with IP, location, device — and lights up the chain board.",
"By the time they stop, you have a map of exactly how far they got and how fast they moved.",
"Chains work on paper too: print the decoys, leave them in a drawer."]))
con = _bchain_tables()
chains = con.execute("SELECT * FROM bchain WHERE user_id=? ORDER BY id DESC LIMIT 20", (uid,)).fetchall()
clist = ""
for ch in chains:
hops = con.execute("SELECT * FROM bchain_hops WHERE chain_row=? ORDER BY seq", (ch["id"],)).fetchall()
fired = sum(1 for h in hops if h["fired_ts"])
clist += f'◈ {esc(ch["name"])} {fired}/{len(hops)} hops fired'
body = f"""
TRAP CHAIN
Breadcrumb tripwires: each trap a thief trips hands them the next one — and tells you every step of their path through your files.
New chain
{('
Your chains' + clist + '
') if clist else ''}
""" + flow("map the path a thief takes through your files", [
"you arm a 4-hop chain and get 4 unique URLs plus 4 decoy notes.",
"hop 1's URL goes inside a file called RESTORE_PASSWORDS_HERE.txt on the desktop.",
"its decoy text says 'real vault: ' — bait for whoever opened the file.",
"them opens the file, clicks the link (a blank 404) — your inbox pings: hop 1, their IP, their city.",
"they follow the 'vault' link — hop 2 fires. Then 3. The board draws their path in real time.",
"when the chain fully burns you get one summary alert with the whole timeline."]) + how([
"Hop 1 is a plain tripwire. Hops 2+ hide inside the previous hop's decoy note — following the trail IS the confession.",
"Every fire logs IP, geolocation, device, timestamp, and alerts your inbox instantly.",
"The board shows the chain as a diagram: armed hops wait in green, fired ones glow red with their details.",
"Fully-burned chains fire one final summary alert with the complete timeline.",
"Decoy text is fully editable before you plant it — make it fit where it lives."])
body += gloss([("hop","one tripwire in the chain"),("decoy","plausible text that carries the next hop's URL"),("burn","a fully-tripped chain"),("board","the live diagram of the chain's state")])
body += agent_card('POST /api/tchain/create name= nhops=', 'curl -X POST https://dark0rbits.thetempleofdoom.com/api/tchain/create -d "name=laptop" -d "nhops=4" -H "Cookie: dark0rbits_tok=…"', 'GET /api/tchain/status?chain_id= → per-hop state.')
return page("tchain", body)
@app.route("/tchain", methods=["POST"])
def tchain_create():
uid = current_user_id()
if not uid: return page("tchain", "
login required
")
name = (param("name") or "chain")[:80]
try: nhops = min(8, max(2, int(param("nhops") or 4)))
except Exception: nhops = 4
con = _bchain_tables()
chain_id = secrets.token_urlsafe(6)
cur = con.execute("INSERT INTO bchain(user_id,chain_id,name,created) VALUES(?,?,?,?)", (uid, chain_id, esc(name), int(time.time())))
row_id = cur.lastrowid
for seq in range(nhops):
con.execute("INSERT INTO bchain_hops(chain_row,seq,token) VALUES(?,?,?)", (row_id, seq, secrets.token_urlsafe(10)))
con.commit()
return Response(status=302, headers={"Location": f"/tchain/board?id={chain_id}"})
@app.route("/tchain/board")
def tchain_board():
uid = current_user_id()
if not uid: return page("tchain", "
login required
")
chain_id = param("id") or ""
ch = _bchain_get(uid, chain_id)
if not ch: return page("tchain", "
unknown chain
")
# render hop cards with decoy text + plant instructions
hop_html = ""
nhops = len(ch["hops"])
for h in ch["hops"]:
url = f"{SITE}/tc/{h['token']}"
if h["fired_ts"]:
geo = enrich_ip(h["fired_ip"]) or {}
where = f"{geo.get('city','—')}, {geo.get('countryCode','')} · {geo.get('isp','')}" if geo else "—"
state = f'FIRED {time.strftime("%b %d %H:%M", time.localtime(h["fired_ts"]))} · {esc(h["fired_ip"])} · {esc(where)} {esc((h["fired_ua"] or "")[:80])}'
else:
state = 'WAITING'
decoy = ""
if h["seq"] < nhops - 1:
nxt = ch["hops"][h["seq"] + 1]
decoy = (f'
"""
return page("tchain", body)
@app.route("/tc/")
def bchain_fire(token):
con = _bchain_tables()
h = con.execute("SELECT * FROM bchain_hops WHERE token=?", (token,)).fetchone()
if not h: return "Not Found", 404
ip = request.headers.get("X-Real-IP") or request.remote_addr or "?"
ua = request.headers.get("User-Agent", "")
first = not h["fired_ts"]
con.execute("UPDATE bchain_hops SET fired_ts=?, fired_ip=?, fired_ua=? WHERE id=?",
(int(time.time()), ip, ua[:200], h["id"]))
con.commit()
ch = con.execute("SELECT * FROM bchain WHERE id=?", (h["chain_row"],)).fetchone()
if ch and ch["user_id"]:
geo = enrich_ip(ip)
where = f" — {geo.get('city','')}, {geo.get('countryCode','')} · {geo.get('isp','')}" if geo else ""
all_hops = con.execute("SELECT * FROM bchain_hops WHERE chain_row=? ORDER BY seq", (h["chain_row"],)).fetchall()
if first and all(x["fired_ts"] for x in all_hops):
body = f"🔗 TRAP CHAIN FULLY BURNED: '{ch['name']}' — every hop tripped. Timeline on the board."
else:
body = f"🔗 TRAP CHAIN hop {h['seq']+1} fired: '{ch['name']}' — IP {esc(ip)}{esc(where)} · device {esc(ua[:80])}"
con.execute("INSERT INTO messages(user_id,sender,body,created) VALUES(?,?,?,?)", (ch["user_id"], "operator-bot", body, int(time.time())))
con.commit()
return "Not Found", 404
@app.route("/api/tchain/create", methods=["POST"])
def api_tchain_create():
uid = key_user() or current_user_id()
if not uid: return jsonify({"ok": False, "error": "auth required"}), 401
r = rate_limit("tchain", 20, 60)
if r: return r
name = (param("name") or "chain")[:80]
try: nhops = min(8, max(2, int(param("nhops") or 4)))
except Exception: nhops = 4
con = _bchain_tables()
chain_id = secrets.token_urlsafe(6)
cur = con.execute("INSERT INTO bchain(user_id,chain_id,name,created) VALUES(?,?,?,?)", (uid, chain_id, esc(name), int(time.time())))
row_id = cur.lastrowid
hops = []
for seq in range(nhops):
tok = secrets.token_urlsafe(10)
con.execute("INSERT INTO bchain_hops(chain_row,seq,token) VALUES(?,?,?)", (row_id, seq, tok))
hops.append({"seq": seq, "tripwire": f"{SITE}/tc/{tok}"})
con.commit()
return jsonify({"ok": True, "chain_id": chain_id, "hops": hops})
@app.route("/api/tchain/status")
def api_tchain_status():
uid = key_user() or current_user_id()
if not uid: return jsonify({"ok": False, "error": "auth required"}), 401
ch = _bchain_get(uid, param("chain_id") or "")
if not ch: return jsonify({"ok": False, "error": "unknown chain"}), 404
hops = [{"seq": h["seq"], "fired": bool(h["fired_ts"]), "fired_ts": h["fired_ts"], "ip": h["fired_ip"]} for h in ch["hops"]]
return jsonify({"ok": True, "name": ch["row"]["name"], "hops": hops})
# ---------- END TOOL: TRAP CHAIN ----------
# ---------- 9. OPERATOR CONSOLE ----------
@app.route("/admin", methods=["GET", "POST"])
def admin():
if request.method == "POST" and request.form.get("pw") == ADMIN_PW:
resp = Response(status=302); resp.headers["Location"] = "/admin"
resp.set_cookie("dark0rbits_admin", secrets.token_urlsafe(16), max_age=86400, httponly=True)
return resp
if not request.cookies.get("dark0rbits_admin"):
return page("track", '
OPERATOR
')
con = db()
msgs = con.execute("SELECT m.*, u.username FROM messages m JOIN users u ON u.id=m.user_id ORDER BY m.id DESC LIMIT 100").fetchall()
msgs_html = "".join(f'
'
opens = con.execute("SELECT te.*, tr.filename FROM track_events te JOIN trackables tr ON tr.id=te.trackable_id ORDER BY te.id DESC LIMIT 30").fetchall()
opens_html = "".join(f"
" for o in opens)
reply_to = param("reply") or ""
reply_html = ""
if reply_to:
r = con.execute("SELECT username FROM users WHERE id=?", (reply_to,)).fetchone()
if r: reply_html = f'
Reply to {esc(r["username"])}
'
return page("track", f"""
OPERATOR CONSOLE
All customer messages{msgs_html}
Reply
{reply_html}
File open events
File
IP
Device
When
{opens_html}
""")
# ---------- INDEX (hacker landing) ----------
@app.route("/")
def index():
ip = request.headers.get("X-Real-IP") or request.remote_addr
st, b = http(f"http://ip-api.com/json/{ip}?fields=66846719")
d = jf(b) or {}
uid = current_user_id()
con = db()
n_sms = con.execute("SELECT COUNT(*) c FROM sms_rentals").fetchone()["c"]
n_px = con.execute("SELECT COUNT(*) c FROM proxy_checks").fetchone()["c"]
tools = [
("ip","IP INTEL","Geo, ASN, ISP, VPN/hosting flags, rDNS — your IP auto-detected, any target on demand.","◈","INTEL"),
("card","CARD CHECK","Luhn + BIN: issuer bank, brand, type, country, prepaid risk flags. Nothing stored, nothing charged.","◈","INTEL"),
("eh","MAIL FORENSICS","Paste headers or drop a .eml → true origin IP + geo, relay delays, SPF/DKIM/DMARC verdicts, spoof flags.","◈","INTEL"),
("phone","PHONE LOOKUP","OSINT on any number: carrier, line type, region, timezones + free deep-dive leads. VOIP/fake detection.","◈","INTEL"),
("user","USERNAME SLEUTH","One handle → probed across 16 platforms in parallel. Find where the human lives online.","◈","INTEL"),
("domain","DOMAIN RECON","RDAP registration, full DNS, certificate-log subdomain discovery. Passive recon, free.","◈","INTEL"),
("forensics","IMAGE FORENSICS","Deep EXIF (all IFDs), decoded GPS + map links, XMP trails, embedded thumbnails, ELA — expose doctored photos.","◈","INTEL"),
("sms","SMS RENTAL","Disposable numbers, 30-min windows, instant refund on cancel.","◈","ACQUIRE"),
("mail","BURNER MAIL","Receive-only mailboxes, 7–90 days, live countdown. Codes & confirmations without an identity.","◈","ACQUIRE"),
("proxy","PROXY LAB","Residential egress testing on the Pleiades rail — same gateway keys fleet-wide.","◈","ACQUIRE"),
("deaddrop","DEAD-DROP","AES-GCM encrypted notes that burn after N reads or TTL. Optional password. No trace left.","◈","ACQUIRE"),
("steg","STEGO LAB","Hide secret text inside a normal PNG — invisible, password-encrypted, scattered. Live capacity meter.","◈","OPERATE"),
("track","TRACK FILE","Send an image or file, learn who opened it: IP, city, ISP, device, language — instantly in your inbox.","◈","HUNT"),
("canary","CANARY TRAPS","Tripwires: stealth links, pixels, fake-credential honeytokens, honeyfile baits — instant alerts with IP + geo when touched.","◈","HUNT"),
("shot","SCREENSHOT","Headless-Chromium PNG capture of any page. Agents: poll the status API.","◈","HUNT"),
("score","FRAUD-SCORE","Composite 0-100 risk: IP intel + disposable-email + BIN heuristics, with full breakdown.","◈","HUNT"),
("tools","FREE TOOLS","DNS resolver, HTTP header inspector, JWT decoder, hasher, generators.","◈","UTILITY"),
("dms","DEAD MAN SWITCH","Arm a switch, check in on schedule, and your pre-written letters seal as burn-after-read dead-drops the moment you go quiet.","◈","Operate"),
("chain","HASH CHAINS","Chain-of-custody logs where every entry hashes onto the last — any edit, delete or reorder breaks the chain at the exact link. Export a JSON receipt as proof.","◈","HUNT"),
("ghost","GHOST TEXT","Hide secret messages inside innocent-looking text with invisible zero-width characters — looks identical, survives copy-paste on plain-text channels.","◈","OPERATE"),
("chaff","CHAFF","One passphrase in, a complete consistent fake identity out — same seed always regenerates the same persona, and nothing is ever stored.","◈","OPERATE"),
("tracer","LEAK TRACER","Every recipient gets their own invisible-marked copy of a doc. When it leaks, paste the text and the marks name the leaker.","◈","HUNT"),
("traceout","TRACEOUT","Pure-python traceroute with per-hop rDNS + geolocation and run history.","◈","INTEL"),
("tchain","TRAP CHAIN","Breadcrumb tripwires: each trap a thief trips hands them the next — your board maps their exact path with IP + geo per hop.","◈","HUNT"),
("passport","AGENT PASSPORT","Machine-readable trust badge for your bots. Agents are first-class here.","◈","ACCOUNT"),
]
tcards = "".join(
f'
'
for href, name, desc, ico, cat in tools)
stat = f"you're connecting from {esc(d.get('query','?'))} · {esc(d.get('country',''))}"
cta = ('' if uid else '')
from markupsafe import escape as _e
stat_line = '▸ ' + stat + '' if stat else ""
body = f"""
$ ./dark0rbits --intro ▊
The toolbox that treats you like an operator, not a product.
No KYC. No email. No meters — every tool is FREE. Every tool has a JSON API, so scripts and agents are first-class customers.
{stat_line}
{cta}
{tcards}
NO KYCALL FREEAGENT-FIRST APIs{n_sms} SMS RENTALS SERVED{n_px} PROXY CHECKS
For agents: machine catalog at /llms.txt, OpenAPI at /openapi.json, metered keys at /keys.
For humans: click a card. That's it.
"""
return page("home", body)
@app.route("/favicon.svg")
def favicon():
svg = ''
return Response(svg, mimetype="image/svg+xml")
@app.route("/og.png")
def og_img():
from PIL import Image, ImageDraw
im = Image.new("RGB", (1200, 630), (7, 10, 19))
dr = ImageDraw.Draw(im)
for i in range(260):
import random as _r
_r.seed(i)
x, y = _r.randint(0, 1199), _r.randint(0, 629)
dr.ellipse([x, y, x+2, y+2], fill=(200+i%55, 210, 255))
dr.ellipse([480, 190, 720, 430], outline=(167, 139, 250), width=4)
dr.ellipse([455, 165, 745, 455], outline=(111, 214, 255), width=2)
try:
from PIL import ImageFont
f = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf", 84)
f2 = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf", 26)
except Exception:
f = f2 = None
dr.text((600, 290), "DARK0RBITS", fill=(255, 201, 77), anchor="mm", font=f)
dr.text((600, 390), "no-KYC network toolbox · everything free · agents welcome", fill=(147, 160, 194), anchor="mm", font=f2)
buf = io.BytesIO(); im.save(buf, "PNG")
return Response(buf.getvalue(), mimetype="image/png")
@app.route("/health")
def health(): return jsonify({"ok": True, "service": "dark0rbits", "version": "3.0"})
# REDIRECT legacy auriga hostname → dark0rbits
@app.before_request
def _dr_legacy_redirect():
host = (request.host or "").lower()
if host.startswith("auriga.") or host == "auriga.thetempleofdoom.com":
return redirect("https://dark0rbits.thetempleofdoom.com" + request.full_path.rstrip("?"), code=301)
return None
# REDACT-REDIRECT
@app.errorhandler(404)
def not_found(e):
if request.path.startswith("/api/"):
return jsonify({"ok": False, "error": "no such endpoint", "path": request.path}), 404
body = """
404 — LOST SIGNAL
This page drifted off the map. The tools are all still here:
"""
return page("home", body), 404
# ---------- MAG-LAB (browser magstripe studio, closed-loop only) ----------
_MAG_POLICY = (
"MAG-LAB encodes CLOSED-LOOP cards only: your own gift, loyalty, membership, "
"event or staff cards. Payment-network tracks (bank/debit/credit layouts, "
"13-19 digit Luhn-valid PANs, bank service codes 101/121/201-220, EMV/JCOP "
"dumps) are refused at encode AND decode. This is a hard policy, not a "
"toggle you can switch off.")
def _mag_sentinel(track):
"""True if a track looks like a payment-network card rather than closed-loop."""
import re as _re
t = (track or "").strip()
if not t:
return False
body = t[1:] if t[0] in "%;" else t
pan = _re.sub(r"[^0-9]", "", body.split("^")[0] if "^" in body else (body.split("=")[0] if "=" in body else body))
if pan and 13 <= len(pan) <= 19:
s, alt = 0, False
for ch in reversed(pan):
d = ord(ch) - 48
if alt:
d *= 2
if d > 9:
d -= 9
s += d
alt = not alt
if s % 10 == 0:
return True
m = _re.search(r"\^([0-9]{4})([0-9]{3})", t)
if m and m.group(2)[0] in ("1", "2"):
return True
m = _re.search(r"=([0-9]{4})([0-9]{3})", t)
if m and m.group(2)[0] in ("1", "2"):
return True
return False
_MAGLAB_HTML = r"""
MAG LAB
Browser magstripe studio — Chrome + Web Serial talks straight to your MSR605/606-class writer. No drivers, no desktop app, any OS. Encode, read, decode, batch-issue closed-loop cards: gift, loyalty, membership, event tickets, staff badges.
POLICY __POLICY__
CONNECT
not connected
Chrome/Edge/Opera on Windows, macOS, Linux or ChromeOS. Firefox/Safari do not ship Web Serial. Writer must be an MSR605/606 or compatible serial MagStripe encoder.
paste any track to see its structure decoded (read-only field map; payment shapes are masked)
API(agent-first — 30c/encode, 20c/card batch, via key)
__AGENT__
"""
@app.route("/maglab")
def maglab():
body = _MAGLAB_HTML.replace("__POLICY__", _MAG_POLICY)
body = body.replace("__AGENT__", agent_card(
"POST /api/maglab/encode {t1,t2} · POST /api/maglab/batch {rows:[{label,value}]}",
"curl -X POST " + SITE + "/api/maglab/encode -H 'Authorization: Bearer KEY' -d '{\"t2\":\";GIFT000123=4321?\"}'",
"Closed-loop magstripe studio. Encode validates + LRC-checks (30c), batch issues up to 100 cards with PINs + QR twins (20c/card). Refuses payment-card shapes."))
body += gloss([("ISO 7811", "the magstripe track format standard - track1 79-bit alnum, track2/3 5-bit numeric"),
("LRC", "longitudinal redundancy check - the trailing ? sentinel; wrong LRC = unreadable card"),
("closed-loop", "a card scheme you own end-to-end: your shop issues it, your shop redeems it")])
return page("maglab", body)
@app.route("/api/maglab/encode", methods=["POST"])
def api_maglab_encode():
r = rate_limit("maglab", 20, 60)
if r: return r
uid = key_user() or current_user_id()
if not uid:
return jsonify({"ok": False, "error": "auth required: account session (sign up at /inbox, no KYC) or Authorization: Bearer *** key"}), 401
if not has_pass(uid) and not charge(uid, 30, "maglab encode"):
return jsonify({"ok": False, "error": "insufficient balance", "balance_cents": get_balance(uid), "topup": SITE + "/keys"}), 402
t1 = str(jp("t1") or "").strip()
t2 = str(jp("t2") or "").strip()
if not t1 and not t2:
return jsonify({"ok": False, "error": "at least one track required"}), 400
for t in (t1, t2):
if t and _mag_sentinel(t):
return jsonify({"ok": False, "error": "refused: payment-network card shape detected - " + _MAG_POLICY[:120]}), 403
for name, t in (("t1", t1), ("t2", t2)):
if t and not t.endswith("?"):
return jsonify({"ok": False, "error": name + " missing terminator '?' (LRC sentinel)"}), 400
return jsonify({"ok": True, "ready": True, "t1": t1, "t2": t2})
@app.route("/api/maglab/batch", methods=["POST"])
def api_maglab_batch():
r = rate_limit("maglab_batch", 6, 60)
if r: return r
uid = key_user() or current_user_id()
if not uid:
return jsonify({"ok": False, "error": "auth required: account session (sign up at /inbox, no KYC) or Authorization: Bearer *** key"}), 401
rows = jp("rows")
if not isinstance(rows, list) or not rows:
return jsonify({"ok": False, "error": "rows: array of {label,value} required"}), 400
if len(rows) > 100:
return jsonify({"ok": False, "error": "max 100 cards per batch"}), 400
pas = has_pass(uid)
if not pas and not charge(uid, 20 * len(rows), "maglab batch x%d" % len(rows)):
return jsonify({"ok": False, "error": "insufficient balance", "balance_cents": get_balance(uid), "topup": SITE + "/keys"}), 402
made = []
for i, row in enumerate(rows):
label = str(row.get("label") or ("CARD%03d" % (i + 1)))[:40]
value = str(row.get("value") or "").strip()
if not value:
return jsonify({"ok": False, "error": "row %d: value required" % (i + 1)}), 400
pin = "".join(str(random.randrange(10)) for _ in range(6))
t2 = ";" + re.sub(r"[^A-Z0-9]", "", value.upper()) + "=" + pin + "?"
if _mag_sentinel(t2):
return jsonify({"ok": False, "error": "row %d: refused, payment-card shape" % (i + 1)}), 403
made.append({"label": label, "t2": t2, "pin": pin, "qr": SITE + "/card?card=" + label + ":" + pin})
return jsonify({"ok": True, "count": len(made), "cards": made,
"cost_cents": 0 if pas else 20 * len(rows)})
@app.route("/api/maglab/decode", methods=["POST"])
def api_maglab_decode():
r = rate_limit("maglab_dec", 40, 60)
if r: return r
t = str(jp("track") or "").strip()
if not t:
return jsonify({"ok": False, "error": "track required"}), 400
if _mag_sentinel(t):
return jsonify({"ok": False, "masked": True, "error": "payment-card shape - fields masked by policy"}), 200
t1 = t.startswith("%")
sep = "^" if t1 else "="
body = t[1:] if t[0] in "%;" else t
fields = body.rstrip("?").split(sep)
return jsonify({"ok": True, "track": 1 if t1 else 2,
"format": "ISO7811-A" if t1 else "ISO7811-B",
"fields": [f[:40] for f in fields],
"lrc_sentinel": body.endswith("?"),
"note": "closed-loop decode"})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, threaded=True)