submit.py SMTP :587 + otp_api.py mailbox API, imap_code strict-parse fix, auto.py SPF, login.py uid-select, READMEs

This commit is contained in:
Vlad Gothbreach
2026-10-15 23:02:57 +03:00
parent 830cdcbfaa
commit 51e4c5fd0b
7 changed files with 432 additions and 8 deletions
+40
View File
@@ -52,3 +52,43 @@ journalctl -u mailcatch -n 5 # should log '(relayed)'
Proven: gname `.eu.cc` domains → VPS MX → Gmail inbox, verification code visible in body
(subject `[catch otp-...@domain]`), stored `.eml` on the box.
## submit.py — outbound SMTP (send AS your domain)
Authenticated submission on `:587` (LOGIN, password = `sp` in `env.json`), STARTTLS if
`cert.pem`+`key.pem` are present (self-signed is fine for MUA use). Delivery: direct to
recipient MX on `:25`; if the host blocks outbound 25 (most VPS do), it **falls back to a
Gmail relay** using `gm`/`gp` from `env.json` — `From:` header keeps your domain address.
```
cat >> /root/mailcatch/env.json # merge {"sp": "<random-pass>"} into existing JSON
# self-signed TLS (optional):
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 825 -nodes -subj "/CN=mail.yourdomain"
# systemd: mailsubmit.service, ExecStart=/usr/bin/python3 /root/mailcatch/submit.py
```
Client test (proven E2E: accepted → Gmail INBOX, marker in subject):
```python
import smtplib, ssl
s = smtplib.SMTP("VPS_IP", 587, timeout=45); s.ehlo()
s.starttls(context=ssl._create_unverified_context()); s.ehlo()
s.login("anything@yourdomain", "<sp>")
s.sendmail("me@yourdomain", ["you@gmail.com"],
"From: me@yourdomain\r\nTo: you@gmail.com\r\nSubject: hi\r\n\r\nbody")
```
Note: aiosmtpd 1.4.6 requires the authenticator to return
`AuthResult(success=..., handled=..., auth_data=...)` — plain `bool` authenticates but
leaves `session.authenticated` unset (MAIL FROM → 530). `submit.py` already does it right.
For good inbox placement add SPF: `TXT @ = v=spf1 ip4:VPS_IP ~all` (auto.py does this).
## otp_api.py — HTTP API over the caught mail
Stdlib HTTP on `:2525`, reads the same `mail/` store. Endpoints:
- `GET /next?domain=yourdomain` → `{"address": "userN@yourdomain"}` — next unseen mailbox
- `GET /acquire?address=x@yourdomain&ttl=600` — reserve an exact address
- `GET /latest?address=x@yourdomain&wait=60` → newest message for it; long-polls up to
`wait` seconds; auto-extracts `code` (matches "verification code is : NNNNNN" etc.)
- `GET /list?domain=yourdomain` — known mailboxes with last-seen
- `GET /health` → `{"ok": true, "mails": N}`
Full loop proven E2E: `/next` → register on a site with that address → site mails the OTP
→ public MX → catcher → `/latest?wait=90` returns the code (`CODE VALID: True`).
Deploy: systemd `otpapi.service`, `ExecStart=/usr/bin/python3 /root/mailcatch/otp_api.py`
(WorkingDirectory=/root/mailcatch so it finds `mail/`).
+161
View File
@@ -0,0 +1,161 @@
# -*- coding: utf-8 -*-
"""otp_api.py — HTTP API over the catcher mailbox store (port 2525, stdlib only).
Endpoints:
GET /next?domain=reformwk59.eu.cc -> {"address": "user42@domain"} (least-recently-used free mailbox)
GET /acquire?address=user42@domain&ttl=600 -> lock mailbox to caller (X-Client-Id header optional)
GET /latest?address=user42@domain&wait=60 -> {"found": true, "subject":..., "body":..., "code": "123456", "ts":...}
long-polls up to `wait` seconds for new mail
GET /list?domain=reformwk59.eu.cc -> recent addresses with mail
GET /health -> ok
State: mailboxes.json (address -> {last_used, locked_until, client}) next to script.
Mail source: ../mail/*.eml written by catcher.py (filename contains recipient).
Run on the VPS: python3 otp_api.py (systemd: otpapi.service)
"""
import email as eml
import json
import os
import re
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse, parse_qs
HERE = os.path.dirname(os.path.abspath(__file__))
MAILDIR = os.path.join(HERE, "mail")
STATE_F = os.path.join(HERE, "mailboxes.json")
PORT = int(os.environ.get("OTP_API_PORT") or 2525)
POOL = int(os.environ.get("OTP_POOL") or 500) # user1..userN per domain
CODE_RE = re.compile(r"(?:verification code is|code is|code|код)[:\s]*([0-9]{4,8})", re.I)
def load_state():
try:
return json.load(open(STATE_F, encoding="utf-8"))
except Exception:
return {}
def save_state(st):
tmp = STATE_F + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(st, f)
os.replace(tmp, STATE_F)
def mails_for(address):
"""Scan MAILDIR for .eml whose filename/body contains address; newest first."""
out = []
if not os.path.isdir(MAILDIR):
return out
low = address.lower()
for fn in os.listdir(MAILDIR):
if not fn.endswith(".eml"):
continue
p = os.path.join(MAILDIR, fn)
try:
if low not in fn.lower():
head = open(p, "rb").read(2048).decode(errors="replace").lower()
if low not in head:
continue
raw = open(p, "rb").read()
msg = eml.message_from_bytes(raw)
body = ""
if msg.is_multipart():
for part in msg.walk():
if part.get_content_type() == "text/plain":
body = part.get_payload(decode=True).decode(errors="replace")
break
if not body:
body = str(msg.get_payload())
else:
payload = msg.get_payload(decode=True)
body = payload.decode(errors="replace") if isinstance(payload, bytes) else str(payload or "")
out.append({
"file": fn, "mtime": os.path.getmtime(p),
"subject": str(msg.get("Subject") or ""),
"from": str(msg.get("From") or ""),
"body": body[:4000],
})
except Exception:
continue
out.sort(key=lambda x: -x["mtime"])
return out
class H(BaseHTTPRequestHandler):
def log_message(self, format, *args):
pass
def _json(self, obj, code=200):
b = json.dumps(obj, ensure_ascii=False).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(b)))
self.end_headers()
self.wfile.write(b)
def do_GET(self):
u = urlparse(self.path)
q = {k: v[0] for k, v in parse_qs(u.query).items()}
st = load_state()
now = time.time()
if u.path == "/health":
return self._json({"ok": True, "mails": len(os.listdir(MAILDIR)) if os.path.isdir(MAILDIR) else 0})
if u.path == "/next":
dom = q.get("domain", "").lower()
if not dom:
return self._json({"error": "domain required"}, 400)
taken = {a for a, v in st.items() if a.endswith("@" + dom) and (v.get("locked_until", 0) > now or v.get("last_used", 0) > now - 3600)}
picked = None
for i in range(1, POOL + 1):
cand = "user%d@%s" % (i, dom)
if cand in taken:
continue
picked = cand
break
if not picked:
return self._json({"error": "pool exhausted"}, 503)
st[picked] = {"last_used": now, "locked_until": now + int(q.get("ttl", 600)), "client": self.headers.get("X-Client-Id", "")}
save_state(st)
return self._json({"address": picked})
if u.path == "/acquire":
addr = q.get("address", "").lower()
st[addr] = {"last_used": now, "locked_until": now + int(q.get("ttl", 600)), "client": self.headers.get("X-Client-Id", "")}
save_state(st)
return self._json({"acquired": addr})
if u.path == "/latest":
addr = q.get("address", "").lower()
wait = min(int(q.get("wait", 60)), 300)
since = float(q.get("since", 0))
t0 = time.time()
while True:
ms = [m for m in mails_for(addr) if m["mtime"] > since]
if ms:
m = ms[0]
code = ""
mm = CODE_RE.search(m["body"]) or CODE_RE.search(m["subject"])
if mm:
code = mm.group(1)
return self._json({"found": True, "subject": m["subject"], "from": m["from"],
"body": m["body"][:2000], "code": code, "ts": m["mtime"]})
if time.time() - t0 > wait:
return self._json({"found": False})
time.sleep(2)
if u.path == "/list":
dom = q.get("domain", "").lower()
seen = {}
for fn in os.listdir(MAILDIR) if os.path.isdir(MAILDIR) else []:
mm = re.search(r"catch ([^@\]]+@[^@\]]+)\]", fn)
if mm and (not dom or mm.group(1).endswith(dom)):
seen[mm.group(1)] = max(seen.get(mm.group(1), 0), os.path.getmtime(os.path.join(MAILDIR, fn)))
return self._json({"addresses": sorted(seen, key=lambda a: -seen[a])[:50]})
return self._json({"error": "unknown path"}, 404)
if __name__ == "__main__":
srv = ThreadingHTTPServer(("0.0.0.0", PORT), H)
print("otp_api listening :%d maildir=%s" % (PORT, MAILDIR), flush=True)
srv.serve_forever()
+186
View File
@@ -0,0 +1,186 @@
# -*- coding: utf-8 -*-
"""submit.py — authenticated SMTP submission (port 587) with real outbound delivery.
Clients auth with LOGIN (user = anything@yourdomain, pass = env sp), then mail is
delivered DIRECTLY to recipient MX from the VPS (From: you@yourdomain preserved).
Zero deps beyond aiosmtpd (same as catcher.py). Pure-python MX resolver included.
Run: python3 submit.py (port 587, env file next to script: env.json {sp})
Test: swaks --server VPS --port 587 --auth LOGIN --auth-user me@reformwk59.eu.cc \
--auth-password $SP --to someone@gmail.com --from me@reformwk59.eu.cc
Or python: smtplib.SMTP(host,587) -> starttls() -> login('me@domain', SP) -> sendmail(...)
NOTE: add SPF to the domain for deliverability:
setup_dns.py <domain> --txt "@=v=spf1 ip4:<VPS_IP> ~all"
"""
import asyncio, json, os, re, smtplib, socket, ssl, struct, random, sys, time
from aiosmtpd.controller import Controller
from aiosmtpd.smtp import SMTP as SMTPsrv, LoginPassword, AuthResult
HERE = os.path.dirname(os.path.abspath(__file__))
ENV = json.load(open(os.path.join(HERE, "env.json"))) if os.path.exists(os.path.join(HERE, "env.json")) else {}
SP = ENV.get("sp") or os.environ.get("SUBMIT_PASS") or ""
PORT = int(ENV.get("submit_port") or os.environ.get("SUBMIT_PORT") or 587)
LOG = os.path.join(HERE, "submit.log")
def log(*a):
line = " ".join(str(x) for x in a)
print(time.strftime("[%H:%M:%S]"), line, flush=True)
with open(LOG, "a", encoding="utf-8") as f:
f.write(line + "\n")
# ---------- minimal DNS MX resolver (no deps) ----------
def _qname(name):
return b"".join(bytes([len(p)]) + p.encode() for p in name.split(".") if p) + b"\x00"
def _parse_name(msg, off):
labels, jumped, orig = [], False, off
while True:
ln = msg[off]
if ln == 0:
off += 1
break
if ln & 0xC0 == 0xC0:
ptr = struct.unpack("!H", msg[off:off + 2])[0] & 0x3FFF
if not jumped:
orig = off + 2
off, jumped = ptr, True
continue
labels.append(msg[off + 1:off + 1 + ln].decode(errors="replace"))
off += ln + 1
return ".".join(labels), (orig if jumped else off)
def resolve_mx(domain, timeout=6):
"""Return list of (prio, host) for domain; falls back to A of domain itself."""
tid = random.randint(0, 65535)
q = struct.pack("!HHHHHH", tid, 0x0100, 1, 0, 0, 0) + _qname(domain) + struct.pack("!HH", 15, 1)
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(timeout)
for dns in ("1.1.1.1", "8.8.8.8"):
try:
s.sendto(q, (dns, 53))
msg, _ = s.recvfrom(4096)
ancount = struct.unpack("!H", msg[6:8])[0]
if ancount == 0:
continue
# skip question
_, off = _parse_name(msg, 12)
off += 4
out = []
for _ in range(ancount):
_, off = _parse_name(msg, off)
rtype, rdlen = struct.unpack("!HH", msg[off + 8:off + 12])
rd_start = off + 10
if rtype == 15:
prio = struct.unpack("!H", msg[rd_start:rd_start + 2])[0]
exch, _ = _parse_name(msg, rd_start + 2)
out.append((prio, exch.rstrip(".")))
off = rd_start + rdlen
s.close()
if out:
return sorted(out)
except Exception:
continue
s.close()
except Exception:
pass
try:
socket.gethostbyname(domain)
return [(10, domain.rstrip("."))]
except Exception:
return []
def deliver(mail_from, rcpt, data):
dom = rcpt.split("@")[-1].lower()
mxs = resolve_mx(dom)
errs = []
for prio, host in mxs[:4]:
try:
ip = socket.gethostbyname(host)
s = smtplib.SMTP(ip, 25, timeout=30)
s.ehlo(socket.gethostname() or "submit")
try:
s.starttls(context=ssl.create_default_context())
s.ehlo()
except Exception:
pass
s.sendmail(mail_from, [rcpt], data)
s.quit()
log("DELIVERED", rcpt, "via", host, ip)
return True
except Exception as e:
errs.append("%s:%s:%s" % (host, type(e).__name__, str(e)[:60]))
log("DIRECT FAIL", rcpt, "|".join(errs), "-> trying gmail relay")
return relay_gmail(rcpt, data)
def relay_gmail(rcpt, data):
gm, gp = ENV.get("gm"), ENV.get("gp")
if not gm or not gp:
log("RELAY FAIL no gm/gp in env.json")
return False
try:
s = smtplib.SMTP_SSL("smtp.gmail.com", 465, timeout=45)
s.login(gm, gp)
s.sendmail(gm, [rcpt], data)
s.quit()
log("RELAYED via gmail ->", rcpt)
return True
except Exception as e:
log("RELAY FAIL", rcpt, type(e).__name__, str(e)[:120])
return False
def authenticator(server, session, envelope, mechanism, auth_data):
if not SP:
return AuthResult(success=False, handled=False)
if not isinstance(auth_data, LoginPassword):
return AuthResult(success=False, handled=False)
if auth_data.password.decode(errors="replace") == SP:
return AuthResult(success=True, handled=True, auth_data=auth_data)
return AuthResult(success=False, handled=False)
class SubmitHandler:
async def handle_DATA(self, server, session, envelope):
ok = deliver(envelope.mail_from, envelope.rcpt_tos[0], envelope.content)
return "250 OK" if ok else "451 delivery failed"
def _tls_context():
cert = os.path.join(HERE, "cert.pem")
key = os.path.join(HERE, "key.pem")
if os.path.exists(cert) and os.path.exists(key):
c = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
c.load_cert_chain(cert, key)
return c
return None
def main():
if not SP:
print("FATAL: set sp in env.json or SUBMIT_PASS env", file=sys.stderr)
return 1
c = Controller(SubmitHandler(), hostname="0.0.0.0", port=PORT,
authenticator=authenticator,
auth_required=True, auth_require_tls=False,
tls_context=_tls_context())
c.start()
log("submit listening :%d (auth LOGIN, pass from env)" % PORT)
try:
while True:
time.sleep(3600)
except KeyboardInterrupt:
c.stop()
return 0
if __name__ == "__main__":
sys.exit(main())