Login via our own magic links, 3-step onboarding (domain, DNS records, first send), emails with status timeline, domains, API keys (live/test), webhooks, suppressions, team, usage + plan. Live/Test switch everywhere. Dev mock server + MOUNT.md listing the one-line axum mount and missing API pieces. Verified in a headless browser against the mock (24 screenshots). Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
489 lines
29 KiB
Python
489 lines
29 KiB
Python
#!/usr/bin/env python3
|
|
"""Local stand-in for mail-server, for driving the dashboard without Postgres.
|
|
|
|
Serves the static dashboard from the parent directory and an in-memory copy of
|
|
the documented endpoints (crates/mail-server/README.md + mail-auth README).
|
|
Not a test file; a dev convenience. Python 3.10+, stdlib only.
|
|
|
|
python3 mock/mock_server.py # http://127.0.0.1:8795
|
|
MOCK_BILLING=on python3 mock/mock_server.py # also answers /billing
|
|
|
|
Magic links are not emailed: GET /__mock/last-link returns the verify URL.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import json
|
|
import os
|
|
import secrets
|
|
import sys
|
|
import time
|
|
import uuid
|
|
from datetime import date, datetime, timedelta, timezone
|
|
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
|
from urllib.parse import parse_qs, unquote, urlparse
|
|
|
|
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
PORT = int(os.environ.get("PORT", "8795"))
|
|
BILLING = os.environ.get("MOCK_BILLING", "off") == "on"
|
|
|
|
|
|
def now() -> str:
|
|
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
|
|
|
|
|
|
def ago(minutes: int) -> str:
|
|
return (datetime.now(timezone.utc) - timedelta(minutes=minutes)).strftime("%Y-%m-%dT%H:%M:%S.000Z")
|
|
|
|
|
|
def b64url(b: bytes) -> str:
|
|
return base64.urlsafe_b64encode(b).decode().rstrip("=")
|
|
|
|
|
|
def fake_jwt(email: str) -> str:
|
|
header = b64url(json.dumps({"alg": "EdDSA", "typ": "JWT"}).encode())
|
|
payload = b64url(json.dumps({"sub": "user_" + email.split("@")[0], "email": email,
|
|
"aud": "scribase-mail", "iss": "scribase-mail-auth",
|
|
"exp": int(time.time()) + 3600}).encode())
|
|
return f"{header}.{payload}.{b64url(secrets.token_bytes(32))}"
|
|
|
|
|
|
def dns_records(name: str, status: str = "not_started") -> list[dict]:
|
|
return [
|
|
{"record": "DKIM", "name": "scribase._domainkey", "type": "TXT", "ttl": "Auto", "status": status,
|
|
"value": "p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3xq0" + "A" * 120, "purpose": "Signs your mail so inboxes trust it"},
|
|
{"record": "SPF", "name": "send", "type": "TXT", "ttl": "Auto", "status": status,
|
|
"value": "v=spf1 include:rp.oracleemaildelivery.com ~all", "purpose": "Allows our relay to send for you"},
|
|
{"record": "DMARC", "name": "_dmarc", "type": "TXT", "ttl": "Auto", "status": status,
|
|
"value": "v=DMARC1; p=none; rua=mailto:dmarc@scribase.com", "purpose": "Tells inboxes what to do with forgeries"},
|
|
]
|
|
|
|
|
|
class Store:
|
|
def __init__(self) -> None:
|
|
self.tokens: dict[str, dict] = {}
|
|
self.last_link: str | None = None
|
|
self.accounts: dict[str, dict] = {}
|
|
self.members: dict[str, list[dict]] = {}
|
|
self.invites: dict[str, list[dict]] = {}
|
|
self.domains: dict[str, dict] = {}
|
|
self.keys: dict[str, dict] = {}
|
|
self.key_tokens: dict[str, str] = {}
|
|
self.webhooks: dict[str, dict] = {}
|
|
self.suppressions: dict[str, list[dict]] = {}
|
|
self.emails: dict[str, dict] = {}
|
|
self.audit: dict[str, list[dict]] = {}
|
|
|
|
def seed_account(self, email: str, name: str = "Acme Inc") -> dict:
|
|
aid = str(uuid.uuid4())
|
|
acct = {"object": "account", "id": aid, "name": name, "plan": "free", "status": "active",
|
|
"limits": {"emails_per_day": 100, "emails_per_month": 3000}, "created_at": ago(60 * 24 * 3)}
|
|
self.accounts[aid] = acct
|
|
self.members[aid] = [
|
|
{"object": "member", "user_id": "user_" + email.split("@")[0], "email": email, "role": "owner", "created_at": ago(60 * 24 * 3)},
|
|
{"object": "member", "user_id": "user_dana", "email": "dana@acme.test", "role": "developer", "created_at": ago(60 * 24)},
|
|
]
|
|
self.invites[aid] = [{"object": "invite", "id": str(uuid.uuid4()), "email": "sam@acme.test", "role": "viewer",
|
|
"invited_by": email, "expires_at": ago(-60 * 70), "created_at": ago(30)}]
|
|
did = str(uuid.uuid4())
|
|
self.domains[did] = {"object": "domain", "id": did, "account_id": aid, "name": "acme.test", "status": "pending",
|
|
"created_at": ago(60 * 24 * 2), "region": "eu-frankfurt-1", "return_path": "send",
|
|
"open_tracking": False, "click_tracking": False, "dkim_selector": "scribase",
|
|
"capabilities": {"sending": "enabled", "receiving": "disabled"},
|
|
"records": dns_records("acme.test", "pending"), "verify_count": 0}
|
|
for i, (kname, perm, test) in enumerate([("production", "full_access", False), ("ci", "sending_access", False), ("local-dev", "full_access", True)]):
|
|
kid = str(uuid.uuid4())
|
|
self.keys[kid] = {"id": kid, "account_id": aid, "name": kname, "permission": perm, "domain_id": did if perm == "sending_access" else None,
|
|
"key_prefix": "sk_test_a1b2" if test else f"sk_{'live'}{i}x9", "mode": "test" if test else "live",
|
|
"created_at": ago(60 * 24 * (3 - i)), "last_used_at": ago(5 * (i + 1)) if i < 2 else None}
|
|
wid = str(uuid.uuid4())
|
|
self.webhooks[wid] = {"object": "webhook", "id": wid, "account_id": aid, "created_at": ago(60 * 24), "status": "enabled",
|
|
"endpoint": "https://api.acme.test/webhooks/mail",
|
|
"events": ["email.sent", "email.delivered", "email.bounced", "email.complained", "email.failed"],
|
|
"signing_secret": "whsec_" + b64url(secrets.token_bytes(24))}
|
|
self.suppressions[aid] = [
|
|
{"object": "suppression", "email": "bob@customer.example", "reason": "hard_bounce", "source_email_id": None, "detail": "550 5.1.1 user unknown", "created_at": ago(90)},
|
|
{"object": "suppression", "email": "carol@customer.example", "reason": "complaint", "source_email_id": None, "detail": None, "created_at": ago(400)},
|
|
{"object": "suppression", "email": "old-list@example.org", "reason": "manual", "source_email_id": None, "detail": None, "created_at": ago(60 * 24 * 2)},
|
|
]
|
|
statuses = ["delivered", "delivered", "sent", "bounced", "delivered", "complained", "failed", "queued", "delivered", "scheduled"]
|
|
for i, st in enumerate(statuses):
|
|
eid = str(uuid.uuid4())
|
|
self.emails[eid] = {"object": "email", "id": eid, "account_id": aid, "message_id": f"<{eid[:8]}@acme.test>",
|
|
"to": [f"user{i}@customer.example"], "from": "Acme <hello@acme.test>", "created_at": ago(7 * i + 3),
|
|
"subject": ["Your receipt", "Reset your password", "Welcome to Acme", "Weekly summary", "Invoice 1042"][i % 5],
|
|
"html": "<h1>Hello</h1><p>This is the message body.</p>", "text": "Hello\n\nThis is the message body.",
|
|
"bcc": None, "cc": None, "reply_to": None, "last_event": st,
|
|
"scheduled_at": ago(-120) if st == "scheduled" else None,
|
|
"tags": [{"name": "category", "value": "transactional"}], "test": False}
|
|
self.suppressions[aid][0]["source_email_id"] = [e for e in self.emails.values() if e["last_event"] == "bounced"][0]["id"]
|
|
for i in range(3):
|
|
eid = str(uuid.uuid4())
|
|
self.emails[eid] = {"object": "email", "id": eid, "account_id": aid, "message_id": f"<{eid[:8]}@acme.test>",
|
|
"to": ["delivered@test.scribase.dev" if i else "bounced@test.scribase.dev"], "from": "hello@acme.test",
|
|
"created_at": ago(20 * i + 1), "subject": f"Test send {i + 1}", "html": "<p>test</p>", "text": "test",
|
|
"bcc": None, "cc": None, "reply_to": None, "last_event": "delivered" if i else "bounced",
|
|
"scheduled_at": None, "tags": [], "test": True}
|
|
self.audit[aid] = [{"object": "audit_entry", "id": str(uuid.uuid4()), "actor": {"type": "user", "id": "u", "label": email},
|
|
"action": a, "target": {"type": t, "id": tid}, "detail": {}, "created_at": ago(m)}
|
|
for a, t, tid, m in [("domain.created", "domain", did, 60 * 24 * 2), ("api_key.created", "api_key", "k", 60 * 24), ("webhook.created", "webhook", wid, 60 * 23), ("member.invited", "member", "sam@acme.test", 30)]]
|
|
return acct
|
|
|
|
def audit_add(self, aid: str, actor: str, action: str, ttype: str, tid: str) -> None:
|
|
self.audit.setdefault(aid, []).insert(0, {"object": "audit_entry", "id": str(uuid.uuid4()), "actor": {"type": "user", "id": "u", "label": actor},
|
|
"action": action, "target": {"type": ttype, "id": tid}, "detail": {}, "created_at": now()})
|
|
|
|
|
|
STORE = Store()
|
|
|
|
|
|
class Handler(SimpleHTTPRequestHandler):
|
|
def __init__(self, *a, **kw):
|
|
super().__init__(*a, directory=ROOT, **kw)
|
|
|
|
def log_message(self, fmt, *args): # quieter
|
|
sys.stderr.write("%s %s\n" % (self.command, self.path))
|
|
|
|
def end_headers(self): # static files: never cache while developing
|
|
self.send_header("cache-control", "no-store")
|
|
super().end_headers()
|
|
|
|
# -- helpers -------------------------------------------------------------
|
|
def send_json(self, status: int, body) -> None:
|
|
data = json.dumps(body).encode()
|
|
self.send_response(status)
|
|
self.send_header("content-type", "application/json")
|
|
self.send_header("content-length", str(len(data)))
|
|
self.send_header("cache-control", "no-store")
|
|
self.end_headers()
|
|
self.wfile.write(data)
|
|
|
|
def error(self, status: int, name: str, message: str) -> None:
|
|
self.send_json(status, {"statusCode": status, "name": name, "message": message})
|
|
|
|
def body(self) -> dict:
|
|
n = int(self.headers.get("content-length") or 0)
|
|
return json.loads(self.rfile.read(n) or b"{}") if n else {}
|
|
|
|
def auth(self) -> tuple[str, str, str] | None:
|
|
"""Returns (account_id, actor_email, role) or None after writing an error."""
|
|
h = self.headers.get("authorization", "")
|
|
if not h.startswith("Bearer "):
|
|
self.error(401, "missing_api_key", "Missing API Key")
|
|
return None
|
|
tok = h[7:].strip()
|
|
if tok.startswith("sk_"):
|
|
kid = STORE.key_tokens.get(tok)
|
|
if not kid:
|
|
self.error(401, "validation_error", "API key is invalid")
|
|
return None
|
|
k = STORE.keys[kid]
|
|
return k["account_id"], k["name"], "owner" if k["permission"] == "full_access" else "developer"
|
|
try:
|
|
payload = json.loads(base64.urlsafe_b64decode(tok.split(".")[1] + "=="))
|
|
except Exception:
|
|
self.error(401, "unauthorized", "Session token is invalid or expired.")
|
|
return None
|
|
aid = self.headers.get("x-account-id")
|
|
if not aid:
|
|
self.error(400, "missing_account_id", "Session callers must send the `X-Account-Id` header.")
|
|
return None
|
|
if aid not in STORE.accounts:
|
|
self.error(404, "not_found", "The requested endpoint does not exist.")
|
|
return None
|
|
role = next((m["role"] for m in STORE.members[aid] if m["email"] == payload["email"]), "viewer")
|
|
return aid, payload["email"], role
|
|
|
|
def user(self) -> dict | None:
|
|
h = self.headers.get("authorization", "")
|
|
if not h.startswith("Bearer ") or h[7:].startswith("sk_"):
|
|
self.error(401, "unauthorized", "This endpoint needs a signed-in user (session token), not an API key.")
|
|
return None
|
|
try:
|
|
return json.loads(base64.urlsafe_b64decode(h[7:].split(".")[1] + "=="))
|
|
except Exception:
|
|
self.error(401, "unauthorized", "Session token is invalid or expired.")
|
|
return None
|
|
|
|
# -- routing -------------------------------------------------------------
|
|
def do_GET(self):
|
|
u = urlparse(self.path)
|
|
p, q = u.path.rstrip("/") or "/", parse_qs(u.query)
|
|
seg = p.strip("/").split("/")
|
|
local = os.path.normpath(os.path.join(ROOT, p.lstrip("/")))
|
|
if p == "/" or (local.startswith(ROOT) and os.path.isfile(local)):
|
|
return super().do_GET()
|
|
if p == "/__mock/last-link":
|
|
return self.send_json(200, {"link": STORE.last_link})
|
|
if p == "/healthz":
|
|
return self.send_json(200, {"ok": True, "service": "scribase-mail-mock"})
|
|
if p == "/auth/verify":
|
|
tok = q.get("token", [""])[0]
|
|
row = STORE.tokens.pop(tok, None)
|
|
if not row:
|
|
return self.error(400, "invalid_token", "This link is invalid, expired, or was already used.")
|
|
jwt = fake_jwt(row["email"])
|
|
if not any(row["email"] == m["email"] for ms in STORE.members.values() for m in ms) and os.environ.get("MOCK_EMPTY") != "on":
|
|
STORE.seed_account(row["email"])
|
|
target = f"{row['redirect_to']}#access_token={jwt}&token_type=bearer&expires_in=3600&purpose=magic_link"
|
|
self.send_response(303)
|
|
self.send_header("location", target)
|
|
self.send_header("cache-control", "no-store")
|
|
self.end_headers()
|
|
return None
|
|
if p == "/accounts":
|
|
user = self.user()
|
|
if not user:
|
|
return None
|
|
mine = [dict(a, role=next(m["role"] for m in STORE.members[a["id"]] if m["email"] == user["email"]))
|
|
for a in STORE.accounts.values() if any(m["email"] == user["email"] for m in STORE.members[a["id"]])]
|
|
return self.send_json(200, {"object": "list", "has_more": False, "data": mine})
|
|
if seg[0] in ("billing",) and not BILLING:
|
|
return self.error(404, "not_found", "The requested endpoint does not exist.")
|
|
a = self.auth()
|
|
if not a:
|
|
return None
|
|
aid, actor, role = a
|
|
if seg[0] == "accounts" and len(seg) == 2:
|
|
return self.send_json(200, dict(STORE.accounts[aid], role=role))
|
|
if seg[0] == "accounts" and len(seg) == 3 and seg[2] == "members":
|
|
return self.send_json(200, {"object": "list", "has_more": False, "data": STORE.members[aid], "pending_invites": STORE.invites[aid]})
|
|
if seg[0] == "domains":
|
|
items = [d for d in STORE.domains.values() if d["account_id"] == aid]
|
|
if len(seg) == 1:
|
|
return self.send_json(200, {"object": "list", "has_more": False, "data": [self.public(d) for d in items]})
|
|
d = STORE.domains.get(seg[1])
|
|
return self.send_json(200, self.public(d)) if d and d["account_id"] == aid else self.error(404, "not_found", "Not found")
|
|
if seg[0] == "api-keys":
|
|
return self.send_json(200, {"object": "list", "has_more": False, "data": [self.public(k) for k in STORE.keys.values() if k["account_id"] == aid]})
|
|
if seg[0] == "webhooks":
|
|
items = [w for w in STORE.webhooks.values() if w["account_id"] == aid]
|
|
if len(seg) == 1:
|
|
return self.send_json(200, {"object": "list", "has_more": False, "data": [self.public(w, drop=("signing_secret",)) for w in items]})
|
|
w = STORE.webhooks.get(seg[1])
|
|
if not w or w["account_id"] != aid:
|
|
return self.error(404, "not_found", "Not found")
|
|
if len(seg) == 3: # deliveries: not in the real API yet
|
|
return self.error(404, "not_found", "The requested endpoint does not exist.")
|
|
return self.send_json(200, self.public(w, drop=() if role != "viewer" else ("signing_secret",)))
|
|
if seg[0] == "suppressions":
|
|
return self.send_json(200, {"object": "list", "has_more": False, "data": STORE.suppressions[aid]})
|
|
if seg[0] == "emails":
|
|
items = sorted([e for e in STORE.emails.values() if e["account_id"] == aid], key=lambda e: e["created_at"], reverse=True)
|
|
if len(seg) == 1:
|
|
limit = int(q.get("limit", ["20"])[0])
|
|
return self.send_json(200, {"object": "list", "has_more": len(items) > limit, "data": [self.public(e, drop=("html", "text")) for e in items[:limit]]})
|
|
e = STORE.emails.get(seg[1])
|
|
if not e or e["account_id"] != aid:
|
|
return self.error(404, "not_found", "Not found")
|
|
if len(seg) == 3:
|
|
return self.error(405, "method_not_allowed", "GET not supported here") if seg[2] == "events" else self.error(404, "not_found", "Not found")
|
|
return self.send_json(200, self.public(e))
|
|
if seg[0] == "usage":
|
|
today = date.today()
|
|
start = today.replace(day=1)
|
|
days = []
|
|
for i in range((today - start).days + 1):
|
|
d = start + timedelta(days=i)
|
|
live = (i * 7) % 23 + 4
|
|
days.append({"day": d.isoformat(), "emails_sent": live, "emails_test": (i * 3) % 5, "recipients": live + i % 3})
|
|
totals = {k: sum(x[k] for x in days) for k in ("emails_sent", "emails_test", "recipients")}
|
|
return self.send_json(200, {"object": "usage", "account_id": aid, "from": start.isoformat(), "to": today.isoformat(),
|
|
"totals": totals, "limits": STORE.accounts[aid]["limits"], "days": days})
|
|
if seg[0] == "audit-log":
|
|
return self.send_json(200, {"object": "list", "has_more": False, "data": STORE.audit.get(aid, [])})
|
|
if seg[0] == "billing":
|
|
return self.send_json(200, {"object": "billing", "plan": {"name": "Starter"}, "status": "active", "description": "3,000 emails per month, 100 per day",
|
|
"limits": STORE.accounts[aid]["limits"], "next_plan": "pro", "upgrade_label": "Upgrade to Pro",
|
|
"renews_at": ago(-60 * 24 * 12), "portal_url": "https://billing.example/portal"})
|
|
return self.error(404, "not_found", "The requested endpoint does not exist.")
|
|
|
|
def public(self, obj: dict, drop: tuple = ()) -> dict:
|
|
return {k: v for k, v in obj.items() if k not in ("account_id", "verify_count", *drop)}
|
|
|
|
def do_POST(self):
|
|
p = urlparse(self.path).path.rstrip("/")
|
|
seg = p.strip("/").split("/")
|
|
if p == "/auth/magic-link":
|
|
b = self.body()
|
|
tok = b64url(secrets.token_bytes(32))
|
|
STORE.tokens[tok] = {"email": b["email"].lower(), "redirect_to": b["redirect_to"]}
|
|
STORE.last_link = f"http://127.0.0.1:{PORT}/auth/verify?token={tok}"
|
|
sys.stderr.write(f"magic link for {b['email']}: {STORE.last_link}\n")
|
|
return self.send_json(200, {"ok": True, "message": "If that address can receive mail, a link is on its way.", "expires_in": 900})
|
|
if p == "/accounts":
|
|
user = self.user()
|
|
if not user:
|
|
return None
|
|
name = (self.body().get("name") or "").strip()
|
|
if not name:
|
|
return self.error(422, "missing_required_field", "`name` is required.")
|
|
aid = str(uuid.uuid4())
|
|
STORE.accounts[aid] = {"object": "account", "id": aid, "name": name, "plan": "free", "status": "active", "limits": {}, "created_at": now()}
|
|
STORE.members[aid] = [{"object": "member", "user_id": user["sub"], "email": user["email"], "role": "owner", "created_at": now()}]
|
|
STORE.invites[aid], STORE.suppressions[aid], STORE.audit[aid] = [], [], []
|
|
return self.send_json(201, dict(STORE.accounts[aid], role="owner"))
|
|
if seg[0] == "billing" and not BILLING:
|
|
return self.error(404, "not_found", "The requested endpoint does not exist.")
|
|
a = self.auth()
|
|
if not a:
|
|
return None
|
|
aid, actor, role = a
|
|
b = self.body()
|
|
if seg[0] == "domains" and len(seg) == 1:
|
|
name = (b.get("name") or "").strip().lower()
|
|
if "." not in name:
|
|
return self.error(422, "validation_error", "`name` must be a domain like example.com")
|
|
did = str(uuid.uuid4())
|
|
STORE.domains[did] = {"object": "domain", "id": did, "account_id": aid, "name": name, "status": "not_started", "created_at": now(),
|
|
"region": b.get("region", "eu-frankfurt-1"), "return_path": "send", "open_tracking": bool(b.get("open_tracking")),
|
|
"click_tracking": bool(b.get("click_tracking")), "dkim_selector": "scribase",
|
|
"capabilities": {"sending": "enabled", "receiving": "disabled"}, "records": dns_records(name), "verify_count": 0}
|
|
STORE.audit_add(aid, actor, "domain.created", "domain", did)
|
|
return self.send_json(201, self.public(STORE.domains[did]))
|
|
if seg[0] == "domains" and len(seg) == 3 and seg[2] == "verify":
|
|
d = STORE.domains.get(seg[1])
|
|
if not d or d["account_id"] != aid:
|
|
return self.error(404, "not_found", "Not found")
|
|
d["verify_count"] += 1
|
|
if d["verify_count"] >= 2:
|
|
d["status"] = "verified"
|
|
d["records"] = dns_records(d["name"], "verified")
|
|
else:
|
|
d["status"] = "pending"
|
|
d["records"] = dns_records(d["name"], "failed")
|
|
d["records"][2]["status"] = "verified"
|
|
STORE.audit_add(aid, actor, "domain.verified", "domain", d["id"])
|
|
return self.send_json(200, self.public(d))
|
|
if seg[0] == "api-keys":
|
|
if role not in ("owner", "admin"):
|
|
return self.error(403, "forbidden", f"Your role ({role}) does not allow this action.")
|
|
name = (b.get("name") or "").strip()
|
|
if not name:
|
|
return self.error(422, "missing_required_field", "`name` is required.")
|
|
test = b.get("mode") == "test"
|
|
token = ("sk_test_" if test else "sk_") + b64url(secrets.token_bytes(24))
|
|
kid = str(uuid.uuid4())
|
|
STORE.keys[kid] = {"id": kid, "account_id": aid, "name": name, "permission": b.get("permission", "full_access"), "domain_id": b.get("domain_id"),
|
|
"key_prefix": token[:12] if test else token[:7], "mode": "test" if test else "live", "created_at": now(), "last_used_at": None}
|
|
STORE.key_tokens[token] = kid
|
|
STORE.audit_add(aid, actor, "api_key.created", "api_key", kid)
|
|
return self.send_json(201, {"id": kid, "object": "api_key", "token": token, "mode": "test" if test else "live"})
|
|
if seg[0] == "webhooks" and len(seg) == 1:
|
|
ep = b.get("endpoint") or ""
|
|
if not ep.startswith("https://"):
|
|
return self.error(422, "validation_error", "`endpoint` must be an https:// URL.")
|
|
wid = str(uuid.uuid4())
|
|
STORE.webhooks[wid] = {"object": "webhook", "id": wid, "account_id": aid, "created_at": now(), "status": "enabled", "endpoint": ep,
|
|
"events": b.get("events") or [], "signing_secret": "whsec_" + b64url(secrets.token_bytes(24))}
|
|
STORE.audit_add(aid, actor, "webhook.created", "webhook", wid)
|
|
return self.send_json(201, {"object": "webhook", "id": wid, "signing_secret": STORE.webhooks[wid]["signing_secret"]})
|
|
if seg[0] == "suppressions":
|
|
email = (b.get("email") or "").strip().lower()
|
|
if "@" not in email:
|
|
return self.error(422, "validation_error", "`email` is not a valid address.")
|
|
STORE.suppressions[aid].insert(0, {"object": "suppression", "email": email, "reason": "manual", "source_email_id": None, "detail": None, "created_at": now()})
|
|
return self.send_json(201, {"object": "suppression", "email": email, "reason": "manual"})
|
|
if seg[0] == "emails" and len(seg) == 1:
|
|
frm = b.get("from", "")
|
|
dom = frm.split("@")[-1].rstrip(">")
|
|
d = next((x for x in STORE.domains.values() if x["account_id"] == aid and x["name"] == dom), None)
|
|
if not d or d["status"] != "verified":
|
|
return self.error(403, "validation_error", f"The {dom} domain is not verified. Please, add and verify your domain first.")
|
|
eid = str(uuid.uuid4())
|
|
STORE.emails[eid] = {"object": "email", "id": eid, "account_id": aid, "message_id": f"<{eid[:8]}@{dom}>", "to": b.get("to", []), "from": frm,
|
|
"created_at": now(), "subject": b.get("subject"), "html": b.get("html"), "text": b.get("text"), "bcc": b.get("bcc"),
|
|
"cc": b.get("cc"), "reply_to": b.get("reply_to"), "last_event": "queued", "scheduled_at": None, "tags": b.get("tags") or [], "test": False}
|
|
return self.send_json(200, {"id": eid})
|
|
if seg[0] == "emails" and len(seg) == 3 and seg[2] == "cancel":
|
|
e = STORE.emails.get(seg[1])
|
|
if not e or e["account_id"] != aid:
|
|
return self.error(404, "not_found", "Not found")
|
|
e["last_event"] = "canceled"
|
|
return self.send_json(200, {"object": "email", "id": e["id"]})
|
|
if seg[0] == "accounts" and len(seg) == 3 and seg[2] == "members":
|
|
if role not in ("owner", "admin"):
|
|
return self.error(403, "forbidden", f"Your role ({role}) does not allow this action.")
|
|
email = (b.get("email") or "").lower()
|
|
inv = {"object": "invite", "id": str(uuid.uuid4()), "email": email, "role": b.get("role", "developer"), "invited_by": actor,
|
|
"expires_at": ago(-60 * 72), "created_at": now(), "email_sent": True}
|
|
STORE.invites[aid].append(inv)
|
|
STORE.audit_add(aid, actor, "member.invited", "member", email)
|
|
return self.send_json(201, inv)
|
|
if seg[0] == "billing" and seg[1] == "checkout":
|
|
return self.send_json(200, {"url": f"http://127.0.0.1:{PORT}/#/usage?upgraded=1"})
|
|
return self.error(404, "not_found", "The requested endpoint does not exist.")
|
|
|
|
def do_PATCH(self):
|
|
seg = urlparse(self.path).path.strip("/").split("/")
|
|
a = self.auth()
|
|
if not a:
|
|
return None
|
|
aid, actor, role = a
|
|
b = self.body()
|
|
if seg[0] == "domains" and len(seg) == 2:
|
|
d = STORE.domains.get(seg[1])
|
|
for k in ("open_tracking", "click_tracking"):
|
|
if k in b:
|
|
d[k] = bool(b[k])
|
|
return self.send_json(200, {"object": "domain", "id": d["id"]})
|
|
if seg[0] == "webhooks" and len(seg) == 2:
|
|
w = STORE.webhooks.get(seg[1])
|
|
for k in ("endpoint", "events", "status"):
|
|
if k in b and b[k] is not None:
|
|
w[k] = b[k]
|
|
return self.send_json(200, {"object": "webhook", "id": w["id"]})
|
|
if seg[0] == "accounts" and len(seg) == 2:
|
|
STORE.accounts[aid]["name"] = b.get("name", STORE.accounts[aid]["name"])
|
|
return self.send_json(200, STORE.accounts[aid])
|
|
if seg[0] == "accounts" and len(seg) == 4 and seg[2] == "members":
|
|
m = next((m for m in STORE.members[aid] if m["user_id"] == seg[3]), None)
|
|
if not m:
|
|
return self.error(404, "not_found", "Not found")
|
|
if m["role"] == "owner" and b.get("role") != "owner" and sum(1 for x in STORE.members[aid] if x["role"] == "owner") <= 1:
|
|
return self.error(422, "validation_error", "An account needs at least one owner.")
|
|
m["role"] = b.get("role", m["role"])
|
|
return self.send_json(200, m)
|
|
return self.error(404, "not_found", "The requested endpoint does not exist.")
|
|
|
|
def do_DELETE(self):
|
|
seg = urlparse(self.path).path.strip("/").split("/")
|
|
a = self.auth()
|
|
if not a:
|
|
return None
|
|
aid, actor, role = a
|
|
if seg[0] == "api-keys":
|
|
k = STORE.keys.pop(seg[1], None)
|
|
if k:
|
|
STORE.key_tokens = {t: i for t, i in STORE.key_tokens.items() if i != seg[1]}
|
|
return self.send_json(200, {"object": "api_key", "id": seg[1], "deleted": True})
|
|
if seg[0] == "domains":
|
|
STORE.domains.pop(seg[1], None)
|
|
return self.send_json(200, {"object": "domain", "id": seg[1], "deleted": True})
|
|
if seg[0] == "webhooks":
|
|
STORE.webhooks.pop(seg[1], None)
|
|
return self.send_json(200, {"object": "webhook", "id": seg[1], "deleted": True})
|
|
if seg[0] == "suppressions":
|
|
addr = unquote(seg[1]).lower()
|
|
before = len(STORE.suppressions[aid])
|
|
STORE.suppressions[aid] = [s for s in STORE.suppressions[aid] if s["email"] != addr]
|
|
if len(STORE.suppressions[aid]) == before:
|
|
return self.error(404, "not_found", "Not found")
|
|
return self.send_json(200, {"object": "suppression", "email": addr, "deleted": True})
|
|
if seg[0] == "accounts" and len(seg) == 4 and seg[2] == "members":
|
|
STORE.members[aid] = [m for m in STORE.members[aid] if m["user_id"] != seg[3]]
|
|
return self.send_json(200, {"object": "member", "id": seg[3], "deleted": True})
|
|
if seg[0] == "accounts" and len(seg) == 4 and seg[2] == "invites":
|
|
STORE.invites[aid] = [i for i in STORE.invites[aid] if i["id"] != seg[3]]
|
|
return self.send_json(200, {"object": "invite", "id": seg[3], "deleted": True})
|
|
return self.error(404, "not_found", "The requested endpoint does not exist.")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
srv = ThreadingHTTPServer(("127.0.0.1", PORT), Handler)
|
|
sys.stderr.write(f"mock mail-server + dashboard on http://127.0.0.1:{PORT} (billing: {'on' if BILLING else 'off'})\n")
|
|
try:
|
|
srv.serve_forever()
|
|
except KeyboardInterrupt:
|
|
pass
|