Spaces:
Running
Running
OpenCode Bot commited on
Commit ·
e8cfd54
1
Parent(s): 11d5d1b
Support STARTTLS in Resend proxy
Browse filesFiles changed (2)
- Dockerfile+10-2
- smtp-proxy.py+75-56
2 unmodified lines3456789101112131415162 unmodified linesFROM python:3.13-slimRUN apt-get update \&& apt-get install -y --no-install-recommends ca-certificates tzdata \&& rm -rf /var/lib/apt/lists/* \&& update-ca-certificatesCOPY --from=upstream /new-api /new-apiCOPY smtp-proxy.py /app/smtp-proxy.pyCOPY start.sh /app/start.shRUN chmod +x /app/start.shENV PORT=7860 \TZ=Asia/Shanghai \2 unmodified lines34567891011121314151617181920212223242 unmodified linesFROM python:3.13-slimRUN apt-get update \&& apt-get install -y --no-install-recommends ca-certificates openssl tzdata \&& rm -rf /var/lib/apt/lists/* \&& update-ca-certificatesCOPY --from=upstream /new-api /new-apiCOPY smtp-proxy.py /app/smtp-proxy.pyCOPY start.sh /app/start.shRUN openssl req -x509 -newkey rsa:2048 -nodes \-keyout /app/smtp-proxy.key \-out /usr/local/share/ca-certificates/smtp-proxy.crt \-days 3650 \-subj "/CN=smtp.resend.com" \-addext "subjectAltName=DNS:smtp.resend.com" \&& cp /usr/local/share/ca-certificates/smtp-proxy.crt /app/smtp-proxy.crt \&& update-ca-certificates \&& chmod +x /app/start.shENV PORT=7860 \TZ=Asia/Shanghai \
123456789103 unmodified lines14151617181962 unmodified lines828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201#!/usr/bin/env python3import asyncioimport base64import jsonimport loggingimport osimport reimport urllib.requestfrom email import message_from_bytesfrom email.header import decode_header3 unmodified linesLISTEN_HOST = "127.0.0.1"LISTEN_PORT = 587FALLBACK_API_KEY = os.environ.get("RESEND_API_KEY", "").strip()logging.basicConfig(level=logging.INFO, format="%(asctime)s [smtp-proxy] %(message)s")log = logging.getLogger(__name__)62 unmodified linesreturn False, str(exc)class SMTPSession:def __init__(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter):self.reader = readerself.writer = writerself.mail_from = ""self.rcpts: list[str] = []self.api_key = FALLBACK_API_KEYasync def send(self, line: str) -> None:self.writer.write((line + "\r\n").encode("utf-8"))await self.writer.drain()async def read_line(self) -> str:data = await asyncio.wait_for(self.reader.readline(), timeout=60)if not data:return ""return data.decode("utf-8", errors="replace").rstrip("\r\n")async def handle_auth_plain(self, arg: str) -> None:if not arg:await self.send("334 ")arg = await self.read_line()_, password = parse_plain_auth(arg)self.api_key = password.strip() or self.api_keyawait self.send("235 2.7.0 Authentication successful")async def handle_auth_login(self) -> None:await self.send("334 VXNlcm5hbWU6")await self.read_line()await self.send("334 UGFzc3dvcmQ6")password_b64 = await self.read_line()try:self.api_key = base64.b64decode(password_b64.encode("ascii"), validate=False).decode("utf-8", errors="replace").strip() or self.api_keyexcept Exception:passawait self.send("235 2.7.0 Authentication successful")async def handle_data(self) -> None:await self.send("354 End data with <CR><LF>.<CR><LF>")chunks: list[bytes] = []while True:line = await asyncio.wait_for(self.reader.readline(), timeout=120)if line in {b".\r\n", b".\n", b"."}:breakif line.startswith(b".."):line = line[1:]chunks.append(line)payload = b"".join(chunks)ok, detail = await asyncio.to_thread(send_resend, self.api_key, self.mail_from, self.rcpts, payload)if ok:log.info("sent email via Resend API to=%s", self.rcpts)await self.send("250 2.0.0 OK")else:log.error("Resend delivery failed: %s", detail)await self.send("550 5.0.0 Delivery failed")async def run(self) -> None:await self.send("220 smtp.resend.com ESMTP")while True:line = await self.read_line()if not line:breakcommand, _, arg = line.partition(" ")upper = command.upper()if upper in {"EHLO", "HELO"}:await self.send("250-smtp.resend.com")await self.send("250-AUTH PLAIN LOGIN")await self.send("250 8BITMIME")elif upper == "AUTH":mech, _, rest = arg.partition(" ")if mech.upper() == "PLAIN":await self.handle_auth_plain(rest.strip())elif mech.upper() == "LOGIN":await self.handle_auth_login()else:await self.send("504 5.5.4 Unrecognized authentication type")elif upper == "MAIL":self.mail_from = parse_addr(arg.split(":", 1)[-1])await self.send("250 2.1.0 OK")elif upper == "RCPT":self.rcpts.append(parse_addr(arg.split(":", 1)[-1]))await self.send("250 2.1.5 OK")elif upper == "DATA":await self.handle_data()elif upper == "RSET":self.mail_from = ""self.rcpts = []await self.send("250 2.0.0 OK")elif upper == "NOOP":await self.send("250 2.0.0 OK")elif upper == "QUIT":await self.send("221 2.0.0 Bye")breakelse:await self.send("502 5.5.1 Command not implemented")self.writer.close()await self.writer.wait_closed()async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:try:await SMTPSession(reader, writer).run()except Exception as exc:log.error("SMTP session failed: %s", exc)writer.close()await writer.wait_closed()async def main() -> None:server = await asyncio.start_server(handle_client, LISTEN_HOST, LISTEN_PORT)log.info("listening on %s:%s and forwarding to Resend API", LISTEN_HOST, LISTEN_PORT)async with server:await server.serve_forever()if __name__ == "__main__":asyncio.run(main())1234567891011123 unmodified lines161718192021222362 unmodified lines8687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220#!/usr/bin/env python3import base64import jsonimport loggingimport osimport reimport socketserverimport sslimport threadingimport urllib.requestfrom email import message_from_bytesfrom email.header import decode_header3 unmodified linesLISTEN_HOST = "127.0.0.1"LISTEN_PORT = 587FALLBACK_API_KEY = os.environ.get("RESEND_API_KEY", "").strip()TLS_CERT = "/app/smtp-proxy.crt"TLS_KEY = "/app/smtp-proxy.key"logging.basicConfig(level=logging.INFO, format="%(asctime)s [smtp-proxy] %(message)s")log = logging.getLogger(__name__)62 unmodified linesreturn False, str(exc)class SMTPHandler(socketserver.BaseRequestHandler):def setup(self) -> None:self.conn = self.requestself.conn.settimeout(120)self.reader = self.conn.makefile("rb")self.mail_from = ""self.rcpts: list[str] = []self.api_key = FALLBACK_API_KEYdef send(self, line: str) -> None:self.conn.sendall((line + "\r\n").encode("utf-8"))def read_line(self) -> str:data = self.reader.readline()if not data:return ""return data.decode("utf-8", errors="replace").rstrip("\r\n")def start_tls(self) -> None:self.send("220 2.0.0 Ready to start TLS")self.reader.close()context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)context.load_cert_chain(TLS_CERT, TLS_KEY)self.conn = context.wrap_socket(self.conn, server_side=True)self.conn.settimeout(120)self.reader = self.conn.makefile("rb")def handle_auth_plain(self, arg: str) -> None:if not arg:self.send("334 ")arg = self.read_line()_, password = parse_plain_auth(arg)self.api_key = password.strip() or self.api_keyself.send("235 2.7.0 Authentication successful")def handle_auth_login(self) -> None:self.send("334 VXNlcm5hbWU6")self.read_line()self.send("334 UGFzc3dvcmQ6")password_b64 = self.read_line()try:self.api_key = base64.b64decode(password_b64.encode("ascii"), validate=False).decode("utf-8", errors="replace").strip() or self.api_keyexcept Exception:passself.send("235 2.7.0 Authentication successful")def handle_data(self) -> None:self.send("354 End data with <CR><LF>.<CR><LF>")chunks: list[bytes] = []while True:line = self.reader.readline()if line in {b".\r\n", b".\n", b"."}:breakif line.startswith(b".."):line = line[1:]chunks.append(line)payload = b"".join(chunks)ok, detail = send_resend(self.api_key, self.mail_from, self.rcpts, payload)if ok:log.info("sent email via Resend API to=%s", self.rcpts)self.send("250 2.0.0 OK")else:log.error("Resend delivery failed: %s", detail)self.send("550 5.0.0 Delivery failed")def handle(self) -> None:self.send("220 smtp.resend.com ESMTP")while True:line = self.read_line()if not line:breakcommand, _, arg = line.partition(" ")upper = command.upper()if upper in {"EHLO", "HELO"}:self.send("250-smtp.resend.com")self.send("250-STARTTLS")self.send("250-AUTH PLAIN LOGIN")self.send("250 8BITMIME")elif upper == "STARTTLS":self.start_tls()elif upper == "AUTH":mech, _, rest = arg.partition(" ")if mech.upper() == "PLAIN":self.handle_auth_plain(rest.strip())elif mech.upper() == "LOGIN":self.handle_auth_login()else:self.send("504 5.5.4 Unrecognized authentication type")elif upper == "MAIL":self.mail_from = parse_addr(arg.split(":", 1)[-1])self.send("250 2.1.0 OK")elif upper == "RCPT":self.rcpts.append(parse_addr(arg.split(":", 1)[-1]))self.send("250 2.1.5 OK")elif upper == "DATA":self.handle_data()elif upper == "RSET":self.mail_from = ""self.rcpts = []self.send("250 2.0.0 OK")elif upper == "NOOP":self.send("250 2.0.0 OK")elif upper == "QUIT":self.send("221 2.0.0 Bye")breakelse:self.send("502 5.5.1 Command not implemented")def finish(self) -> None:try:self.reader.close()except Exception:passtry:self.conn.close()except Exception:passclass ThreadingSMTPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):allow_reuse_address = Truedaemon_threads = Truedef main() -> None:server = ThreadingSMTPServer((LISTEN_HOST, LISTEN_PORT), SMTPHandler)log.info("listening on %s:%s and forwarding to Resend API", LISTEN_HOST, LISTEN_PORT)server.serve_forever()if __name__ == "__main__":main()
Dockerfile+10-2
smtp-proxy.py+75-56