diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..e4c28eac0aa0d7b1c6297a446b021638f6ff439f --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +*.ttf filter=lfs diff=lfs merge=lfs -text diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4fd446f2759898366175b9015355261cffab2532 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,19 @@ +FROM python:3.11-slim + +# Hugging Face Spaces run the container as user 1000. +RUN useradd -m -u 1000 user +USER user +ENV HOME=/home/user PATH=/home/user/.local/bin:$PATH +WORKDIR /home/user/app + +COPY --chown=user requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY --chown=user backend ./backend + +# The disk is wiped on restart: real data lives in Firestore and Supabase, so the local +# fallback store only needs a scratch place to exist. This host cannot reach mail servers, so sends wait for the worker on the PC (backend/worker.py). +ENV LOCAL_STORE_DB_PATH=/tmp/local_store.db LOCAL_TICKER=false SEND_ON_THIS_SERVER=false UPLOADS_DIR=/tmp/uploads + +EXPOSE 7860 +CMD ["uvicorn", "backend.app:app", "--host", "0.0.0.0", "--port", "7860"] diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9bf7fd1e7604cc30117a68359214738f31756ba5 --- /dev/null +++ b/README.md @@ -0,0 +1,11 @@ +--- +title: M8ion API +emoji: ๐ฌ +colorFrom: indigo +colorTo: blue +sdk: docker +app_port: 7860 +pinned: false +--- + +M8ion backend. The web app is hosted separately. diff --git a/backend/__init__.py b/backend/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..109a593a24a62981cecfd761acfa80410a23bb81 --- /dev/null +++ b/backend/__init__.py @@ -0,0 +1 @@ +from backend import config # noqa: F401 (side effect: loads .env before anything else) diff --git a/backend/accounts.py b/backend/accounts.py new file mode 100644 index 0000000000000000000000000000000000000000..adb881ec1cd8a81ebe5f891d6cf2a2cce4e615a5 --- /dev/null +++ b/backend/accounts.py @@ -0,0 +1,176 @@ +""" +Individual and organisation accounts (docs/product/account-types.md). + +Every account is one or the other, and the two are kept apart on the server: + + accounts/{uid} โ {account_type, plan, created_at} + +The type is written only from this module, by a server action: set once at registration, or +changed by `upgrade_to_organization`. There is no route that takes a type from a request body +after registration, and no client write path to this document. + +An individual works inside one personal org (orgs/{id}.kind == "personal"), so the same engine +serves both. `check_org_access` is what keeps an individual out of organisation orgs and the +reverse. + +Accounts that existed before this module have no document. They are treated as organisations +(each already belongs to an org) until scripts/migrate_account_types.py writes the document. +""" + +from __future__ import annotations + +from datetime import datetime, timezone + +from backend import firestore_client as db +from backend import orgs + +INDIVIDUAL = "individual" +ORGANIZATION = "organization" +ACCOUNT_TYPES = (INDIVIDUAL, ORGANIZATION) + +PERSONAL_KIND = "personal" + +# Plan keys. Prices live in docs/product/account-types.md; nothing here bills anyone yet. +INDIVIDUAL_PLANS = ("free", "plus") +ORG_PLANS = ("starter", "growth", "scale") +DEFAULT_ORG_PLAN = "starter" + + +class AccountError(Exception): + """Raised for an invalid account choice or change.""" + + +def _path(uid: str) -> str: + return f"accounts/{uid}" + + +def _now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def get_account(uid: str) -> dict | None: + """The stored account document, or None when there isn't one.""" + return db.get_doc(_path(uid)) + + +def account_type_of(uid: str) -> str | None: + """The account's type. A person with no document who already belongs to an org is a + legacy organisation account; a person with neither has not chosen yet (None).""" + account = get_account(uid) + if account: + return account["account_type"] + return ORGANIZATION if orgs.list_orgs_for_user(uid) else None + + +def describe(uid: str) -> dict: + """What the sign-in redirect and the account gate need.""" + account = get_account(uid) + account_type = account["account_type"] if account else account_type_of(uid) + default_plan = None + if account_type == ORGANIZATION: + default_plan = DEFAULT_ORG_PLAN + elif account_type == INDIVIDUAL: + default_plan = "free" + identity = db.get_doc(f"identity/{uid}") or {} + return { + "account_type": account_type, + "plan": (account or {}).get("plan", default_plan), + "legacy": account is None and account_type is not None, + "identity": identity.get("status", "not_started"), + } + + +def _check_plan(account_type: str, plan: str | None) -> str: + if account_type == INDIVIDUAL: + plan = plan or "free" + if plan not in INDIVIDUAL_PLANS: + raise AccountError(f"Unknown individual plan {plan!r}") + else: + plan = plan or DEFAULT_ORG_PLAN + if plan not in ORG_PLANS: + raise AccountError(f"Unknown organisation plan {plan!r}") + return plan + + +def register(uid: str, account_type: str, plan: str | None = None, name: str = "") -> dict: + """Sets the account type, once. An individual gets a personal org to work in; an + organisation gets the org named `name`. Legacy organisations (no document yet) may + formalise as organizations; nothing else can be re-registered.""" + if account_type not in ACCOUNT_TYPES: + raise AccountError("Choose an individual or an organisation account") + existing = account_type_of(uid) + if get_account(uid) or (existing is not None and existing != account_type) or ( + existing == INDIVIDUAL + ): + raise AccountError("This account type is already set and can't be changed here") + plan = _check_plan(account_type, plan) + name = (name or "").strip() + + org_id = None + if account_type == INDIVIDUAL: + org_id = orgs.create_org(uid, name or "Personal", kind=PERSONAL_KIND) + elif existing is None: + if not name: + raise AccountError("Give the organisation a name") + org_id = orgs.create_org(uid, name) + db.set_doc(_path(uid), {"account_type": account_type, "plan": plan, "created_at": _now()}) + return describe(uid) | {"org_id": org_id} + + +def ensure_organization(uid: str) -> None: + """Used when an org is created by someone with no type yet: they become an organisation.""" + if get_account(uid) is None and account_type_of(uid) is None: + db.set_doc(_path(uid), {"account_type": ORGANIZATION, "plan": DEFAULT_ORG_PLAN, "created_at": _now()}) + + +def require_organization(uid: str) -> None: + """Refuses individual accounts. A person with no type yet is allowed through; they + become an organisation by the action that follows.""" + if account_type_of(uid) == INDIVIDUAL: + raise orgs.PermissionError_("This is for organisation accounts") + + +def can_join_org(uid: str) -> None: + """An invite can only be accepted by an organisation account (or a new person).""" + if account_type_of(uid) == INDIVIDUAL: + raise orgs.PermissionError_( + "Individual accounts can't join an organisation. Sign up with another address to accept this invite." + ) + + +def check_org_access(uid: str, org: dict) -> None: + """Keeps the two areas apart: personal orgs for individuals, every other org for + organisation accounts. Raises PermissionError_ otherwise.""" + personal = org.get("kind") == PERSONAL_KIND + account_type = account_type_of(uid) + if account_type is None: + return + if personal and account_type != INDIVIDUAL: + raise orgs.PermissionError_("This belongs to an individual account") + if not personal and account_type != ORGANIZATION: + raise orgs.PermissionError_("This belongs to an organisation account") + + +def is_personal(org_id: str) -> bool: + return orgs.get_org(org_id).get("kind") == PERSONAL_KIND + + +def upgrade_to_organization(uid: str, plan: str, org_name: str) -> dict: + """The one way an individual becomes an organisation. Server-side only: no route calls it + yet, because it needs the organisation plan and identity check first. Their personal org + (and everything in it) becomes the organisation, so nothing is lost.""" + account = get_account(uid) + if not account or account["account_type"] != INDIVIDUAL: + raise AccountError("Only an individual account can be upgraded") + plan = _check_plan(ORGANIZATION, plan) + org_name = (org_name or "").strip() + if not org_name: + raise AccountError("Give the organisation a name") + personal = [oid for oid in orgs.list_orgs_for_user(uid) if is_personal(oid)] + for org_id in personal: + org = orgs.get_org(org_id) + org.pop("kind", None) + org["name"] = org_name + db.set_doc(f"orgs/{org_id}", org) + db.set_doc(_path(uid), {**account, "account_type": ORGANIZATION, "plan": plan, "upgraded_at": _now()}) + return describe(uid) diff --git a/backend/api_access.py b/backend/api_access.py new file mode 100644 index 0000000000000000000000000000000000000000..ee5c634168b873991115a0d0a905bf84a437008c --- /dev/null +++ b/backend/api_access.py @@ -0,0 +1,262 @@ +""" +Lets other products send email through an organisation's connected mailboxes. + +An owner creates an API key in Settings. A product sends with it: + + POST /v1/messages Authorization: Bearer m8_... + {"to": ["a@x.com"], "subject": "...", "html": "
...
", "mailbox_id": "optional"} + +and checks the result with GET /v1/messages/{id}. Messages go out through the same sending +pool, mailbox daily limit, hourly cap and unsubscribe list as campaigns. + +Keys are stored only as a SHA-256 hash; the key itself is shown once, when it is made. +""" + +from __future__ import annotations + +import hashlib +import html as html_lib +import logging +import re +import secrets +import threading +import uuid +from datetime import datetime, timezone + +from backend import firestore_client as db +from backend import mailboxes, mailer_client, orgs, rate_limiter, sending, settings, unsubscribe +from backend.mock_mailer import AuthError, ConnectionFailure + +log = logging.getLogger("m8ion.api") + +KEY_PREFIX = "m8_" +MAX_RECIPIENTS = 50 +MAX_KEYS = 20 +_EMAIL = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$") + + +class ApiError(Exception): + """A problem the calling product should see, with the HTTP status to send.""" + + def __init__(self, status: int, message: str): + super().__init__(message) + self.status = status + + +def _now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def _hash(raw: str) -> str: + return hashlib.sha256(raw.encode("utf-8")).hexdigest() + + +def _keys_prefix(org_id: str) -> str: + return f"orgs/{org_id}/api_keys/" + + +def _message_path(org_id: str, message_id: str) -> str: + return f"orgs/{org_id}/api_messages/{message_id}" + + +def _queue_path(org_id: str, message_id: str) -> str: + return f"queued_api_messages/{org_id}_{message_id}" + + +# --- Keys ---------------------------------------------------------------------- + +def _public(key_id: str, doc: dict) -> dict: + return {k: doc.get(k) for k in ("name", "hint", "created_at", "last_used_at", "revoked_at")} | {"id": key_id} + + +def list_keys(org_id: str, actor_uid: str) -> list[dict]: + orgs.require_permission(org_id, actor_uid, "manage_settings") + prefix = _keys_prefix(org_id) + keys = [_public(path[len(prefix):], doc) for path, doc in db.query_prefix(prefix).items()] + return sorted(keys, key=lambda k: k.get("created_at") or "", reverse=True) + + +def create_key(org_id: str, actor_uid: str, name: str) -> dict: + """Makes a key and returns it once, in full. Only its hash is kept.""" + orgs.require_permission(org_id, actor_uid, "manage_settings") + name = (name or "").strip()[:60] + if not name: + raise ValueError("Give the key a name, such as the product that will use it") + active = [k for k in list_keys(org_id, actor_uid) if not k.get("revoked_at")] + if len(active) >= MAX_KEYS: + raise ValueError(f"An organisation can have up to {MAX_KEYS} keys. Revoke one first.") + raw = KEY_PREFIX + secrets.token_urlsafe(32) + key_id = uuid.uuid4().hex + doc = {"name": name, "hint": raw[:7] + "โฆ" + raw[-4:], "hash": _hash(raw), "created_by": actor_uid, + "created_at": _now(), "last_used_at": None, "revoked_at": None} + db.set_doc(_keys_prefix(org_id) + key_id, doc) + db.set_doc(f"api_key_index/{doc['hash']}", {"org_id": org_id, "key_id": key_id}) + return _public(key_id, doc) | {"key": raw} + + +def revoke_key(org_id: str, actor_uid: str, key_id: str) -> None: + orgs.require_permission(org_id, actor_uid, "manage_settings") + doc = db.get_doc(_keys_prefix(org_id) + key_id) + if doc is None: + raise orgs.NotFoundError("No such key") + db.update_doc(_keys_prefix(org_id) + key_id, {"revoked_at": _now()}) + db.delete_doc(f"api_key_index/{doc['hash']}") + + +def authenticate(authorization: str) -> tuple[str, str]: + """Turns an 'Authorization: Bearer m8_...' header into (org_id, key_id).""" + raw = authorization[7:].strip() if authorization.lower().startswith("bearer ") else "" + if not raw.startswith(KEY_PREFIX): + raise ApiError(401, "Send your API key as 'Authorization: Bearer m8_...'") + entry = db.get_doc(f"api_key_index/{_hash(raw)}") + doc = db.get_doc(_keys_prefix(entry["org_id"]) + entry["key_id"]) if entry else None + if not entry or not doc or doc.get("revoked_at"): + raise ApiError(401, "This API key is not valid or was revoked") + db.update_doc(_keys_prefix(entry["org_id"]) + entry["key_id"], {"last_used_at": _now()}) + return entry["org_id"], entry["key_id"] + + +# --- Messages ------------------------------------------------------------------ + +def _pick_mailbox(org_id: str, mailbox_id: str | None) -> tuple[str, dict]: + boxes = mailboxes.list_mailboxes(org_id) + if mailbox_id: + box = boxes.get(mailbox_id) + if box is None: + raise ApiError(404, "No mailbox with that id in this organisation") + else: + default = settings.email_settings(org_id).get("default_mailbox_id") or "" + verified = [i for i, b in boxes.items() if b.get("status") == "verified"] + mailbox_id = default if default in verified else (verified[0] if len(verified) == 1 else "") + if not mailbox_id: + raise ApiError(400, "Say which mailbox to send from with mailbox_id, or set a default mailbox in Settings") + box = boxes[mailbox_id] + if box.get("status") != "verified": + raise ApiError(409, "That mailbox is not working. Fix it in M8ion, then try again.") + return mailbox_id, box + + +def send_message(org_id: str, key_id: str, body: dict) -> dict: + """Checks the request, reserves room under the limits and queues the message. Returns at once.""" + to = body.get("to") + to = [to] if isinstance(to, str) else to + if not isinstance(to, list) or not to: + raise ApiError(400, "'to' must be an address or a list of addresses") + to = [str(a).strip() for a in to] + if len(to) > MAX_RECIPIENTS: + raise ApiError(400, f"Up to {MAX_RECIPIENTS} addresses per request") + bad = [a for a in to if not _EMAIL.match(a)] + if bad: + raise ApiError(400, f"Not an email address: {', '.join(bad[:5])}") + subject = str(body.get("subject") or "").strip() + if not subject: + raise ApiError(400, "'subject' is required") + html_body = str(body.get("html") or "") + if not html_body: + text = str(body.get("text") or "") + if not text: + raise ApiError(400, "Send the message as 'html' or 'text'") + html_body = "" + html_lib.escape(text).replace("\n", "
") + "
Please confirm your email address to join {org_name}'s list.
" + f'' + f"If you did not ask for this, ignore this email and nothing will happen.
" + ) + mailer = mailer_client.get_mailer(connection["kind"], mailboxes.get_decrypted_credentials(org_id, key["mailbox_connection_id"])) + try: + mailer.send(to_addr=email, subject=f"Confirm your email for {orgs.get_org(org_id)['name']}", body=body) + except (AuthError, ConnectionFailure) as exc: + raise CollectError(503, "Could not send the confirmation email. Try again later.") from exc + + +def _record_consent(org_id: str, row_id: str, key_id: str, email: str) -> None: + db.set_doc(_consent_path(org_id, row_id), { + "key_id": key_id, + "email_hash": hashlib.sha256(email.lower().encode()).hexdigest(), + "confirmed_at": _now().isoformat(), + }) + + +def confirm(token: str) -> str: + """Turns a pending sign-up into a row. Returns "confirmed", "expired" or "invalid".""" + pending = db.get_doc(_pending_path(token)) + if pending is None: + return "invalid" + if datetime.fromisoformat(pending["expires_at"]) < _now(): + db.delete_doc(_pending_path(token)) + return "expired" + values = json.loads(decrypt(pending["encrypted_values"])) + org_id = pending["org_id"] + db.delete_doc(_pending_path(token)) # single use, even if the insert below fails + try: + row_id = databases.insert_row(org_id, pending["database_id"], values) + except orgs.NotFoundError: + return "invalid" # the list was deleted since + workbook.mark_stale(org_id) + email_column = _email_column(databases.get_database(org_id, pending["database_id"])) + _record_consent(org_id, row_id, pending["key_id"], values.get(email_column or "", "")) + key = db.get_doc(_key_path(org_id, pending["key_id"])) + if key: + _send_welcome(org_id, key, row_id) + return "confirmed" diff --git a/backend/collect_api.py b/backend/collect_api.py new file mode 100644 index 0000000000000000000000000000000000000000..2818d73759c6d2d98c279dc392216640a7f2d68d --- /dev/null +++ b/backend/collect_api.py @@ -0,0 +1,92 @@ +""" +The public face of Collect (docs/blueprint/adr/0006) โ the "DMZ". Exactly these routes and +nothing else are reachable without signing in, and each one only calls backend/collect.py. + +It is an APIRouter so the main app can include it today, and `collect_app` is the same router +as a standalone ASGI app for deploying on its own later. + +Cross-origin: the snippet sends its JSON as text/plain, which browsers treat as a "simple" +request (no preflight), and this module sets Access-Control-Allow-Origin per key itself. The +site-wide CORS middleware in app.py is for the signed-in app and stays out of the way. +""" + +from __future__ import annotations + +import html +import json +from pathlib import Path + +from fastapi import APIRouter, FastAPI, Request +from fastapi.responses import HTMLResponse, JSONResponse, Response + +from backend import collect + +router = APIRouter() +_SNIPPET_PATH = Path(__file__).parent / "static" / "m8ion.js" + + +def _client_ip(request: Request) -> str: + # Behind a proxy the first X-Forwarded-For entry is the visitor. Only trusted as a rate-limit + # bucket, never for anything that grants access. + forwarded = request.headers.get("x-forwarded-for", "") + if forwarded: + return forwarded.split(",")[0].strip() + return request.client.host if request.client else "unknown" + + +def _with_cors(response: Response, public_key: str, origin: str | None) -> Response: + allowed = collect.allowed_origin(public_key, origin) + if allowed: + response.headers["Access-Control-Allow-Origin"] = allowed + response.headers["Vary"] = "Origin" + return response + + +@router.post("/collect/{public_key}") +async def submit(public_key: str, request: Request): + origin = request.headers.get("origin") + raw = await request.body() + if len(raw) > 16_000: + return _with_cors(JSONResponse({"detail": "Submission is too large"}, status_code=413), public_key, origin) + try: + payload = json.loads(raw) + except ValueError: + return _with_cors(JSONResponse({"detail": "Malformed submission"}, status_code=400), public_key, origin) + try: + result = collect.submit(public_key, payload, origin, _client_ip(request)) + response = JSONResponse(result) + except collect.CollectError as exc: + response = JSONResponse({"detail": str(exc)}, status_code=exc.status) + return _with_cors(response, public_key, origin) + + +_PAGE = """ +{message}
""" + +_CONFIRM_TEXT = { + "confirmed": ("You're on the list", "Thanks, your email address is confirmed. You can close this page."), + "expired": ("This link has expired", "Please sign up again from the form to get a new confirmation email."), + "invalid": ("This link is no longer valid", "It may already have been used. If you are not on the list yet, sign up again."), +} + + +@router.get("/collect/confirm/{token}", response_class=HTMLResponse) +def confirm(token: str): + title, message = _CONFIRM_TEXT[collect.confirm(token)] + return HTMLResponse(_PAGE.format(title=html.escape(title), message=html.escape(message))) + + +@router.get("/m8ion.js") +def snippet(): + return Response( + _SNIPPET_PATH.read_text(encoding="utf-8"), + media_type="application/javascript", + headers={"Cache-Control": "public, max-age=300", "Access-Control-Allow-Origin": "*"}, + ) + + +collect_app = FastAPI(title="M8ion Collect") +collect_app.include_router(router) diff --git a/backend/config.py b/backend/config.py new file mode 100644 index 0000000000000000000000000000000000000000..3d5d3c0a31fdb3fee1c66d99210e44883ea63c5f --- /dev/null +++ b/backend/config.py @@ -0,0 +1,9 @@ +""" +Loads .env into the process environment before anything else in backend/ reads os.environ. +Imported by backend/__init__.py so every submodule sees a populated environment regardless +of import order. +""" + +from dotenv import load_dotenv + +load_dotenv() diff --git a/backend/core/__init__.py b/backend/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/core/constants.py b/backend/core/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..99c9596b040f954958620bcdb6924212c0438a95 --- /dev/null +++ b/backend/core/constants.py @@ -0,0 +1,204 @@ +""" +Central registry for cross-cutting, iteration-prone values. + +This is the ONE place values like these are defined โ every other module imports from +here, never hand-copies a number or a list. See docs/blueprint/blueprint.md and +docs/product/checklist.md ("central intelligence... registry") for why this file exists: +these are exactly the values that change a lot across iterations, and a change here should +be a visible, deliberate moment, not a silent edit buried in an unrelated diff. + +scripts/run_tests.py diffs this file against the last commit on every test run and prints +a notice (not a failure) listing what changed, so a change here is never silent. + +Every value below marked "prototype placeholder" is not a business decision โ it exists so +local development and tests have something concrete to run against, and is expected to be +replaced with a real, deliberately-chosen number before Phase 2. +""" + +from __future__ import annotations + +# --------------------------------------------------------------------------- +# Versioning +# --------------------------------------------------------------------------- + +# Application version. Bump on every meaningful release (Phase 4 onward, this drives +# docs/general/CHANGELOG.md entries). +APP_VERSION = "0.1.0-proto" + +# Schema version for the data model. Bump when a migration changes stored-data shape in a +# way that old rows won't automatically satisfy โ not on every schema tweak. +SCHEMA_VERSION = "0.1.0" + +# --------------------------------------------------------------------------- +# Org roles โ see docs/blueprint/blueprint.md "Core entities" +# --------------------------------------------------------------------------- + +# Ranked low to high. An action gated at a given role is allowed for that role and every +# role ranked above it (e.g. a check gated at "operator" also passes for "admin"/"owner"). +ROLE_RANK: dict[str, int] = { + "viewer": 0, + "operator": 1, + "editor": 1, + "admin": 2, + "owner": 3, +} + +# What a role can be allowed to do. Seeing the org's results is not on this list: every +# member can always see them. Labels are shown to owners when they set up a role. +PERMISSIONS: dict[str, str] = { + "edit_lists": "Add and change lists and sign-up forms", + "edit_emails": "Create and change saved emails and looks", + "send": "Send campaigns", + "manage_mailboxes": "Connect and manage mailboxes", + "manage_settings": "Change organisation settings", + "manage_team": "Invite people and change their roles", +} + +# Roles every org starts with. Owner always has everything and can't be changed; the +# others are starting points an owner can edit. Custom roles sit beside these. +BUILTIN_ROLES: dict[str, dict] = { + "owner": {"name": "Owner", "permissions": list(PERMISSIONS)}, + "admin": {"name": "Admin", "permissions": list(PERMISSIONS)}, + "editor": {"name": "Editor", "permissions": ["edit_lists", "edit_emails", "send"]}, + "viewer": {"name": "Viewer", "permissions": []}, + "director": {"name": "Director", "permissions": []}, + "accountant": {"name": "Accountant", "permissions": []}, + "marketer": {"name": "Marketer", "permissions": ["edit_lists", "edit_emails", "send"]}, + "auditor": {"name": "Auditor", "permissions": []}, +} + +# The areas of an organisation (/org/{inviter_html} invited you to join {org_html} on M8ion as {role_html}.
" + f'' + f"The link works for {INVITE_TTL_DAYS} days. Sign in or sign up with this address ({invite['email']}).
" + ) + try: + mailer = mailer_client.get_mailer(boxes[cid]["kind"], mailboxes.get_decrypted_credentials(org_id, cid)) + try: + mailer.send(to_addr=invite["email"], subject=f"Join {org_name} on M8ion", body=body) + finally: + close = getattr(mailer, "close", None) + if close: + close() + except Exception: # noqa: BLE001 โ a failed courtesy email must not fail the invite + return False + return True diff --git a/backend/local_mode.py b/backend/local_mode.py new file mode 100644 index 0000000000000000000000000000000000000000..e48392e0be516e73ab19cca53a32478c55310ae8 --- /dev/null +++ b/backend/local_mode.py @@ -0,0 +1,15 @@ +""" +LOCAL_MODE gates every real-external-service call in the backend behind a local, +zero-provisioning substitute โ same principle as the prior single-operator build's +local dev path (see the archived README in ../M8ion-archived-2026-09-23.zip for the +original rationale), rebuilt fresh for the org/role model. + +Defaults to true: no real GCP/Firebase project has been provisioned yet (see +docs/blueprint/blueprint.md and the Phase 0 brainstorm โ billing isn't enabled), so +local-only is the only mode that currently works. Flip to false in .env once a real +Firebase project exists and backend/firestore_client.py's real branch is implemented. +""" + +import os + +LOCAL_MODE = os.getenv("LOCAL_MODE", "true").lower() == "true" diff --git a/backend/local_store.py b/backend/local_store.py new file mode 100644 index 0000000000000000000000000000000000000000..a9b5c3ae0b1036d1968637d05a41923991deeb3e --- /dev/null +++ b/backend/local_store.py @@ -0,0 +1,94 @@ +""" +A local, SQLite-backed stand-in for Firestore's document-path model: one generic table, +keyed by a slash-delimited path (e.g. "orgs/abc123" or "orgs/abc123/members/uid1"), value +is a JSON blob. Enough to build and test the org/role model with zero external services. + +Not a full Firestore emulator โ no query engine, no transactions across paths. Just get / +set / update / delete by exact path, plus a prefix scan for "list documents under this +collection", which is all the org/role model needs. See backend/firestore_client.py for the +seam that swaps this out for the real Firebase Admin SDK once a GCP project exists. +""" + +from __future__ import annotations + +import json +import sqlite3 +import threading +from contextlib import closing +from pathlib import Path + +_DEFAULT_DB_PATH = "local_store.db" +_lock = threading.Lock() +_db_path = _DEFAULT_DB_PATH + + +def init_local_store(db_path: str | None = None) -> None: + """(Re)point the store at a given SQLite file and ensure its table exists. Call this + once at process/test startup โ every other function in this module uses whatever + path was set here last.""" + global _db_path + _db_path = db_path or _DEFAULT_DB_PATH + with closing(_connect()) as conn: + with conn: + conn.execute( + "CREATE TABLE IF NOT EXISTS firestore_docs (path TEXT PRIMARY KEY, data TEXT NOT NULL)" + ) + + +def _connect() -> sqlite3.Connection: + parent = Path(_db_path).parent + if str(parent) not in ("", "."): + parent.mkdir(parents=True, exist_ok=True) + return sqlite3.connect(_db_path) + + +def get_doc(path: str) -> dict | None: + with _lock, closing(_connect()) as conn: + row = conn.execute("SELECT data FROM firestore_docs WHERE path = ?", (path,)).fetchone() + return json.loads(row[0]) if row else None + + +def set_doc(path: str, data: dict) -> None: + with _lock, closing(_connect()) as conn: + with conn: + conn.execute( + "INSERT INTO firestore_docs (path, data) VALUES (?, ?) " + "ON CONFLICT(path) DO UPDATE SET data = excluded.data", + (path, json.dumps(data)), + ) + + +def update_doc(path: str, partial: dict) -> dict: + """Merge partial into the existing doc (shallow merge, Firestore .update() semantics + for top-level fields). Raises if the doc doesn't exist โ matches Firestore behavior.""" + existing = get_doc(path) + if existing is None: + raise KeyError(f"No document at {path!r} to update") + existing.update(partial) + set_doc(path, existing) + return existing + + +def delete_doc(path: str) -> None: + with _lock, closing(_connect()) as conn: + with conn: + conn.execute("DELETE FROM firestore_docs WHERE path = ?", (path,)) + + +def query_prefix(prefix: str) -> dict[str, dict]: + """Direct children of `prefix` only (a collection path, e.g. "orgs/abc123/members/"), + keyed by their full path โ matches real Firestore's .collection().stream() semantics, + which never reaches into a deeper nested subcollection. A naive string-prefix match would + also catch e.g. "orgs/x/databases/db1/rows/row1" when listing "orgs/x/databases/", which + real Firestore's collection() never would, so the remainder past the prefix is required + to contain no further "/".""" + like_pattern = f"{prefix}%" + with _lock, closing(_connect()) as conn: + rows = conn.execute( + "SELECT path, data FROM firestore_docs WHERE path LIKE ?", (like_pattern,) + ).fetchall() + return { + path: json.loads(data) + for path, data in rows + if "/" not in path[len(prefix):] + } diff --git a/backend/mailboxes.py b/backend/mailboxes.py new file mode 100644 index 0000000000000000000000000000000000000000..82533c26e8e812f4d7ab32a9695e3d3eeb597268 --- /dev/null +++ b/backend/mailboxes.py @@ -0,0 +1,402 @@ +""" +Mailbox connections โ the relay identity an org sends through (docs/blueprint/adr/0001). +Two kinds, both stored the same way once connected: "oauth" (Gmail/Outlook/Yahoo โ see +backend/core/constants.py SUPPORTED_OAUTH_PROVIDERS) and "smtp" (hosting-provider mailboxes, +raw host/port/username/password). Credentials are encrypted at rest via backend.crypto_utils +(the prototype stand-in for ADR-0002's GCP KMS envelope encryption). + +Verification is the 3-OTP round-trip from SRS FR-6: send unique OTPs from the connected +mailbox to M8ion's own test mailbox, then confirm receipt/content/metadata match before the +connection is usable for real sends. The five failure states below are SRS FR-7, verbatim. +""" + +from __future__ import annotations + +import imaplib +import json +import re +import uuid +from datetime import datetime, timedelta, timezone + +from backend import delivery +from backend import firestore_client as db +from backend import mailer_client +from backend import orgs +from backend.core.constants import ( + MAILBOX_CREDENTIAL_CHANGE_DAYS, + MAILBOX_DAILY_LIMIT_MAX, + SYSTEM_SENDER_ADDRESS_PROTO, + SYSTEM_TEST_MAILBOX_ADDRESS_PROTO, + SUPPORTED_OAUTH_PROVIDERS, + VERIFICATION_OTP_COUNT, +) +from backend.crypto_utils import decrypt, encrypt +from backend.mock_mailer import AuthError, ConnectionFailure, MockInbox, MockMailer + +# Stands in for "M8ion's own test mailbox" until a real domain/inbox exists โ used for the +# mock round-trip (REAL_SEND_ENABLED=false). The real round-trip (true) has no inbox to +# read back yet (that needs IMAP, unbuilt โ see _verify_real's docstring), so it sends to +# SYSTEM_SENDER_ADDRESS_PROTO instead, the one real mailbox this project actually holds. +SYSTEM_TEST_INBOX = MockInbox() + +# SRS FR-7, worded exactly as specified. +FAILURE_MESSAGES = { + "auth_rejected": "We couldn't sign in to that mailbox. Double-check the email and password, then try again.", + "connection_failed": "We couldn't reach that mail server. Check the server address and port, or confirm with your email provider that SMTP access is enabled.", + "silent_failure": "We couldn't verify delivery. Contact support and we'll help you troubleshoot.", + "unreliable": "This mailbox is only delivering some of the time, which usually means intermittent throttling from your provider. We recommend resolving this before relying on it for real sends.", + "content_mismatch": "Something didn't match during verification. This connection has been flagged for manual review.", + "imap_failed": "Sending works, but we couldn't sign in to the incoming (IMAP) side. Check the IMAP server, port, username and password. We need it to show you delays, bounces and replies.", +} + +# Honest scope for the real (non-mocked) path: auth + send are genuinely verified; +# arrival isn't, since reading a real inbox back needs IMAP (Phase 2, unbuilt). +VERIFIED_REAL_MESSAGE = ( + "Your credentials were accepted and a test message was sent through your mail server. " + "We can't yet confirm it arrived โ check the inbox yourself for full certainty." +) + + +SEND_FAILED_MESSAGE = ( + "We signed in to that mailbox, but your provider refused the test message. " + "Check that sending is allowed for this account, then try again." +) + + +class ValidationError(Exception): + pass + + +def _now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def _connection_path(org_id: str, connection_id: str) -> str: + return f"orgs/{org_id}/mailboxes/{connection_id}" + + +def connect_mailbox(org_id: str, actor_uid: str, kind: str, credentials: dict) -> str: + """Registers a new, not-yet-verified mailbox connection. An org can have more than one + (SRS FR-5). Requires admin or owner (SRS: mailbox management is an org-management + action, not a day-to-day sending one).""" + orgs.require_permission(org_id, actor_uid, "manage_mailboxes") + + if kind == "oauth": + provider = credentials.get("provider") + if provider not in SUPPORTED_OAUTH_PROVIDERS: + raise ValidationError(f"Unsupported OAuth provider {provider!r}") + elif kind == "smtp": + required = {"host", "port", "username", "password"} + missing = required - credentials.keys() + if missing: + raise ValidationError(f"SMTP connection missing fields: {missing}") + credentials = _clean_imap(credentials, required=True) + # Spaces in an app password are display grouping, never part of it. + credentials = {**credentials, "password": "".join(str(credentials["password"]).split())} + else: + raise ValidationError(f"Unknown mailbox kind {kind!r}") + + # The sending address isn't a secret โ it's the From: on every message this connection + # sends โ so it's kept plain alongside the encrypted blob rather than requiring a + # decrypt just to list connections (SRS FR-5's list view needs this on every load). + email = credentials.get("username") if kind == "smtp" else credentials.get("email") + + connection_id = uuid.uuid4().hex + db.set_doc( + _connection_path(org_id, connection_id), + { + "kind": kind, + "email": email, + "has_imap": bool(credentials.get("imap_host")), + "encrypted_credentials": encrypt(json.dumps(credentials)), + "status": "pending_verification", + "status_message": None, + "created_at": _now(), + "verified_at": None, + }, + ) + return connection_id + + +def _clean_imap(credentials: dict, required: bool) -> dict: + """Checks the incoming (IMAP) half of an SMTP mailbox. Both halves are needed: SMTP sends, + IMAP reads back what the provider did with the message (delays, bounces, replies). The IMAP + user and password may be left out when they are the same as the SMTP ones.""" + host = str(credentials.get("imap_host") or "").strip() + if not host: + if required: + raise ValidationError("Add the incoming (IMAP) server too. M8ion needs it to show delays, bounces and replies.") + return credentials + try: + port = int(credentials.get("imap_port") or 993) + except (TypeError, ValueError) as exc: + raise ValidationError("The IMAP port must be a number, usually 993") from exc + if not 1 <= port <= 65535: + raise ValidationError("The IMAP port must be a number, usually 993") + cleaned = {**credentials, "imap_host": host, "imap_port": port} + for key in ("imap_username", "imap_password"): + if not str(cleaned.get(key) or "").strip(): + cleaned.pop(key, None) + if cleaned.get("imap_password"): + cleaned["imap_password"] = "".join(str(cleaned["imap_password"]).split()) + return cleaned + + +def get_mailbox(org_id: str, connection_id: str) -> dict: + doc = db.get_doc(_connection_path(org_id, connection_id)) + if doc is None: + raise orgs.NotFoundError(f"No mailbox connection {connection_id!r} for org {org_id!r}") + return doc + + +def list_mailboxes(org_id: str) -> dict[str, dict]: + prefix = f"orgs/{org_id}/mailboxes/" + docs = db.query_prefix(prefix) + return {path[len(prefix):]: data for path, data in docs.items()} + + +def set_dismissed(org_id: str, actor_uid: str, connection_id: str, dismissed: bool) -> None: + """Hides (or restores) a failed try from the Mailboxes page and the attention counts. The + connection itself is kept, so this is fully reversible.""" + orgs.require_permission(org_id, actor_uid, "manage_mailboxes") + connection = get_mailbox(org_id, connection_id) + if dismissed and connection.get("status") in ("verified", "pending_verification"): + raise ValidationError("Only a mailbox that did not connect can be dismissed") + db.update_doc(_connection_path(org_id, connection_id), {"dismissed": dismissed}) + + +# Per-mailbox choices. Empty / None means "use the organisation's setting". +DEFAULT_MAILBOX_SETTINGS = {"label": "", "from_name": "", "reply_to": "", "daily_limit": 0, "save_sent_copy": None} +_EMAIL = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$") + + +def mailbox_settings(connection: dict) -> dict: + return DEFAULT_MAILBOX_SETTINGS | {k: v for k, v in (connection.get("settings") or {}).items() if k in DEFAULT_MAILBOX_SETTINGS} + + +def update_settings(org_id: str, actor_uid: str, connection_id: str, values: dict) -> dict: + """Saves this mailbox's own sender name, reply-to, daily limit, Sent-copy choice and label.""" + orgs.require_permission(org_id, actor_uid, "manage_mailboxes") + connection = get_mailbox(org_id, connection_id) + unknown = set(values) - set(DEFAULT_MAILBOX_SETTINGS) + if unknown: + raise ValidationError(f"Unknown setting: {', '.join(sorted(unknown))}") + merged = mailbox_settings(connection) | values + for key in ("label", "from_name"): + merged[key] = " ".join(str(merged[key] or "").split()) + if len(merged[key]) > 80: + raise ValidationError("Keep names to 80 characters or fewer") + merged["reply_to"] = str(merged["reply_to"] or "").strip() + if merged["reply_to"] and not _EMAIL.match(merged["reply_to"]): + raise ValidationError("Replies address doesn't look like an email address") + try: + merged["daily_limit"] = int(merged["daily_limit"] or 0) + except (TypeError, ValueError) as exc: + raise ValidationError("Daily limit must be a whole number") from exc + if not 0 <= merged["daily_limit"] <= MAILBOX_DAILY_LIMIT_MAX: + raise ValidationError(f"Daily limit must be between 0 (no limit) and {MAILBOX_DAILY_LIMIT_MAX:,}") + if merged["save_sent_copy"] is not None: + merged["save_sent_copy"] = bool(merged["save_sent_copy"]) + db.update_doc(_connection_path(org_id, connection_id), {"settings": merged}) + return merged + + +def next_credential_change(connection: dict) -> str | None: + """When the sign-in details may next be changed, or None if they may be changed now.""" + last = connection.get("credentials_changed_at") + if not last: + return None + allowed = datetime.fromisoformat(last) + timedelta(days=MAILBOX_CREDENTIAL_CHANGE_DAYS) + return allowed.isoformat() if allowed > datetime.now(timezone.utc) else None + + +def change_credentials(org_id: str, actor_uid: str, connection_id: str, credentials: dict) -> dict: + """Replaces an SMTP mailbox's server and sign-in details, at most once every + MAILBOX_CREDENTIAL_CHANGE_DAYS. The new details are tested first; if the test fails + the old ones stay in place and the change doesn't count. Returns + {status, status_message, changed}.""" + orgs.require_permission(org_id, actor_uid, "manage_mailboxes") + connection = get_mailbox(org_id, connection_id) + if connection["kind"] != "smtp": + raise ValidationError("Only mailboxes connected with server details can be changed here") + wait = next_credential_change(connection) + # Adding the incoming (IMAP) side to a mailbox that has none is allowed at any time: it only + # turns on delivery tracking and does not touch how the mailbox signs in to send. + adding_imap = not connection.get("has_imap") and bool(credentials) and all(k.startswith("imap_") for k in credentials) + if wait and not adding_imap: + raise ValidationError(f"These details were changed recently. They can be changed again from {wait[:10]}.") + current = _decrypted_credentials(connection) + merged = {**current, **{k: v for k, v in credentials.items() if v not in (None, "")}} + missing = {"host", "port", "username", "password"} - merged.keys() + if missing: + raise ValidationError(f"SMTP connection missing fields: {missing}") + merged["password"] = "".join(str(merged["password"]).split()) + merged = _clean_imap(merged, required=False) + if merged == current: + raise ValidationError("Nothing changed") + + path = _connection_path(org_id, connection_id) + if adding_imap: + # Only the incoming side is new: test just that. Re-sending the test emails would be slow + # and is not needed, since sending is unchanged. + if mailer_client.real_send_enabled(): + details = delivery.imap_details(merged) + try: + delivery.open_inbox(details).close() + except (imaplib.IMAP4.error, OSError): + return {"status": "imap_failed", "status_message": FAILURE_MESSAGES["imap_failed"], "changed": False} + db.update_doc(path, {"has_imap": True, "encrypted_credentials": encrypt(json.dumps(merged))}) + return {"status": connection.get("status"), "status_message": connection.get("status_message"), "changed": True} + keep = {k: connection.get(k) for k in ("email", "has_imap", "encrypted_credentials", "status", "status_message", "verified_at")} + db.update_doc(path, {"email": merged["username"], "has_imap": bool(merged.get("imap_host")), "encrypted_credentials": encrypt(json.dumps(merged)), "status": "pending_verification"}) + status = verify_mailbox(org_id, connection_id) + if status != "verified": + message = get_mailbox(org_id, connection_id).get("status_message") + db.update_doc(path, keep) + return {"status": status, "status_message": message, "changed": False} + if not adding_imap: + db.update_doc(path, {"credentials_changed_at": _now()}) + return {"status": status, "status_message": get_mailbox(org_id, connection_id).get("status_message"), "changed": True} + + +def remove_mailbox(org_id: str, actor_uid: str, connection_id: str) -> None: + """Deletes the connection and its stored sign-in details. Past sends keep their record. + Refused while a sign-up form sends its confirmation emails through it.""" + orgs.require_permission(org_id, actor_uid, "manage_mailboxes") + get_mailbox(org_id, connection_id) + users = [ + data.get("name") or "a sign-up form" + for data in db.query_prefix(f"orgs/{org_id}/collect_keys/").values() + if not data.get("revoked") and data.get("mailbox_connection_id") == connection_id + ] + if users: + raise ValidationError(f"{users[0]} sends its confirmation emails from this mailbox. Pick another mailbox there first.") + db.delete_doc(_connection_path(org_id, connection_id)) + for path, brand in db.query_prefix(f"orgs/{org_id}/brands/").items(): + if connection_id in brand.get("mailbox_ids", []): + db.update_doc(path, {"mailbox_ids": [i for i in brand["mailbox_ids"] if i != connection_id]}) + emails_path = f"orgs/{org_id}/settings/emails" + prefs = db.get_doc(emails_path) + if prefs and prefs.get("default_mailbox_id") == connection_id: + db.set_doc(emails_path, {**prefs, "default_mailbox_id": ""}) + + +def get_decrypted_credentials(org_id: str, connection_id: str) -> dict: + """The only sanctioned way to read a connection's plaintext credentials โ callers + outside this module should never touch encrypted_credentials directly.""" + return _decrypted_credentials(get_mailbox(org_id, connection_id)) + + +def _decrypted_credentials(connection: dict) -> dict: + return json.loads(decrypt(connection["encrypted_credentials"])) + + +def verify_mailbox(org_id: str, connection_id: str) -> str: + """Runs the verification round-trip and updates the connection's status. Returns the + final status string. Never raises for an expected failure mode โ those are all + recorded as a status, per SRS FR-7 ("robust support", not a bare exception). + + Branches on mailer_client.real_send_enabled(): mocked (default) runs the full 5-state + round-trip against an in-memory inbox; real runs _verify_real, which can only reach + 3 of those 5 states โ see its docstring for exactly why.""" + connection = get_mailbox(org_id, connection_id) + credentials = _decrypted_credentials(connection) + + if mailer_client.real_send_enabled(): + return _verify_real(org_id, connection_id, connection["kind"], credentials) + return _verify_mock(org_id, connection_id, credentials) + + +def _verify_mock(org_id: str, connection_id: str, credentials: dict) -> str: + try: + mailer = MockMailer(credentials, SYSTEM_TEST_INBOX) + except AuthError: + return _settle(org_id, connection_id, "auth_rejected") + except ConnectionFailure: + return _settle(org_id, connection_id, "connection_failed") + + otps = [uuid.uuid4().hex[:8] for _ in range(VERIFICATION_OTP_COUNT)] + for i, otp in enumerate(otps): + mailer.send( + to_addr=SYSTEM_TEST_MAILBOX_ADDRESS_PROTO, + subject=f"M8ion verification {connection_id} #{i}", + body=f"OTP:{otp}", + ) + + arrived = [ + m for m in SYSTEM_TEST_INBOX.messages_to(SYSTEM_TEST_MAILBOX_ADDRESS_PROTO) + if connection_id in m.subject + ] + + if not arrived: + return _settle(org_id, connection_id, "silent_failure") + + if len(arrived) < len(otps): + _delete_test_messages(arrived) + return _settle(org_id, connection_id, "unreliable") + + expected_bodies = {f"OTP:{otp}" for otp in otps} + arrived_bodies = {m.body for m in arrived} + if arrived_bodies != expected_bodies: + _delete_test_messages(arrived) + return _settle(org_id, connection_id, "content_mismatch") + + _delete_test_messages(arrived) + return _settle(org_id, connection_id, "verified") + + +def _verify_real(org_id: str, connection_id: str, kind: str, credentials: dict) -> str: + """Real SMTP auth + a real send attempt against SYSTEM_SENDER_ADDRESS_PROTO โ the one + real mailbox this project holds credentials for. Can only ever reach "auth_rejected", + "connection_failed", or "verified" โ "silent_failure"/"unreliable"/"content_mismatch" + all require reading the destination inbox back (IMAP) to detect, which isn't built + (Phase 2's bounce-detection work). A "verified" here means auth + send succeeded, not + that arrival was confirmed โ VERIFIED_REAL_MESSAGE says so explicitly in the UI.""" + try: + mailer = mailer_client.get_mailer(kind, credentials) + except AuthError: + return _settle(org_id, connection_id, "auth_rejected") + except (ConnectionFailure, NotImplementedError): + return _settle(org_id, connection_id, "connection_failed") + + try: + for i in range(VERIFICATION_OTP_COUNT): + otp = uuid.uuid4().hex[:8] + mailer.send( + to_addr=SYSTEM_SENDER_ADDRESS_PROTO, + subject=f"M8ion verification {connection_id} #{i}", + body=f"OTP:{otp}", + ) + except (AuthError, ConnectionFailure): + # Sign-in already worked, so telling the person the server was unreachable would be wrong. + return _settle(org_id, connection_id, "connection_failed", message_override=SEND_FAILED_MESSAGE) + + details = delivery.imap_details(credentials) + if details is not None: + try: + delivery.open_inbox(details).close() + except (imaplib.IMAP4.error, OSError): + return _settle(org_id, connection_id, "imap_failed") + return _settle(org_id, connection_id, "verified", message_override=VERIFIED_REAL_MESSAGE) + + +def _delete_test_messages(messages) -> None: + """The test mailbox doesn't keep verification OTPs around once a round-trip is + evaluated, matching the "delete the test mail after test complete" requirement.""" + for m in messages: + if m in SYSTEM_TEST_INBOX.messages: + SYSTEM_TEST_INBOX.messages.remove(m) + + +def _settle(org_id: str, connection_id: str, status: str, message_override: str | None = None) -> str: + path = _connection_path(org_id, connection_id) + db.update_doc( + path, + { + "status": status, + "status_message": message_override if message_override is not None else FAILURE_MESSAGES.get(status), + "verified_at": _now() if status == "verified" else None, + "dismissed": False, # a fresh result is news again, even if the last failure was dismissed + }, + ) + return status diff --git a/backend/mailer_client.py b/backend/mailer_client.py new file mode 100644 index 0000000000000000000000000000000000000000..067982411a8ff2b30d30f2b73971ed609e4d38fb --- /dev/null +++ b/backend/mailer_client.py @@ -0,0 +1,39 @@ +""" +The seam between the sending pipeline (backend/sending.py) and actual mail transport โ +same pattern as backend/firestore_client.py for storage. Independent of LOCAL_MODE on +purpose: LOCAL_MODE governs storage (Firestore vs. the local shim), REAL_SEND_ENABLED +governs mail transport. You can want local storage with a real mailer (exactly the setup +used to verify a real send end-to-end without a GCP project) or, later, real storage with a +mock mailer (safe load-testing against prod-shaped data without actually emailing anyone). + +Mailbox *verification* (backend/mailboxes.py's OTP round-trip) always uses the mock mailer +regardless of this flag โ confirming a real round-trip would need reading the receiving +inbox back (IMAP), which is out of scope until the bounce-detection work in Phase 2 builds +that same scoped read capability. This module only governs the mailer used to actually send +a composed message once a connection is already marked verified. +""" + +from __future__ import annotations + +import os + +from backend.mock_mailer import MockInbox, MockMailer +from backend.smtp_mailer import SMTPMailer + + +def real_send_enabled() -> bool: + return os.getenv("REAL_SEND_ENABLED", "false").lower() == "true" + + +def get_mailer(kind: str, credentials: dict): + if not real_send_enabled(): + return MockMailer(credentials, MockInbox()) + + if kind == "smtp": + return SMTPMailer(credentials) + + raise NotImplementedError( + f"Real sending for mailbox kind {kind!r} isn't wired up yet โ no real Google Cloud " + f"OAuth app exists (see docs/engineering/env-config-reference.md). Set " + f"REAL_SEND_ENABLED=false, or connect this org's mailbox via SMTP instead." + ) diff --git a/backend/messages.py b/backend/messages.py new file mode 100644 index 0000000000000000000000000000000000000000..5b56d6d54f7fa68f45e5f79582fb0ca5381bcc33 --- /dev/null +++ b/backend/messages.py @@ -0,0 +1,52 @@ +""" +The composer's canonical storage (docs/blueprint/adr/0003-html-source-of-truth-composer.md). +HTML is the one stored representation; live preview is just the frontend rendering this +field as-is โ there's no backend computation involved in "preview," which is why there's no +separate preview endpoint/function here. Markdown and the block builder (deferred past +Phase 1 per the ADR) will compile down to this same field, one-way, when they're built. +""" + +from __future__ import annotations + +import json +import uuid +from datetime import datetime, timezone + +from backend import firestore_client as db +from backend import orgs + + +def _now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def _message_path(org_id: str, message_id: str) -> str: + return f"orgs/{org_id}/messages/{message_id}" + + +# Firestore documents stop at 1 MiB; the sent HTML always fits, an editable design with +# uploaded images inside it may not, and is then left out (the HTML alone still reopens). +_MAX_SOURCE_BYTES = 600_000 + + +def create_message(org_id: str, actor_uid: str, subject: str, html_body: str, + mode: str | None = None, design: dict | None = None, automated: bool = False) -> str: + """`mode`/`design` are what the composer was holding when it sent, kept so the email can be + reopened or saved as a preset later exactly as it was built.""" + if not automated: + orgs.require_permission(org_id, actor_uid, "send") + message_id = uuid.uuid4().hex + doc = {"subject": subject, "html_body": html_body, "created_at": _now()} + if mode in ("builder", "html"): + doc["mode"] = mode + if mode == "builder" and isinstance(design, dict) and len(json.dumps(design)) <= _MAX_SOURCE_BYTES: + doc["design"] = design + db.set_doc(_message_path(org_id, message_id), doc) + return message_id + + +def get_message(org_id: str, message_id: str) -> dict: + doc = db.get_doc(_message_path(org_id, message_id)) + if doc is None: + raise orgs.NotFoundError(f"No message {message_id!r} in org {org_id!r}") + return doc diff --git a/backend/mock_mailer.py b/backend/mock_mailer.py new file mode 100644 index 0000000000000000000000000000000000000000..2c604a6eaea2025f37f1155b3100dbd67114cfea --- /dev/null +++ b/backend/mock_mailer.py @@ -0,0 +1,90 @@ +""" +Local stand-in for both halves of a real SMTP round-trip: a mailer that "sends" (an +outbound SMTP client) and an inbox that receives what was sent (standing in for M8ion's +own test mailbox during mailbox verification, per docs/product/srs.md FR-6/FR-7). + +No real network call is ever made here โ matches the prior build's LOCAL_MODE mailer +philosophy. A mailbox connection's credentials dict may carry a "_simulate" key (LOCAL_MODE +/ test-only, never a real credential field) whose value drives one of the five verification +failure states from SRS FR-7, so the whole failure-handling branch can be exercised without +any real mail server: + + "_simulate": "auth_fail" -> AuthError (SRS: "auth rejected") + "_simulate": "connection_fail" -> ConnectionFailure (SRS: "connection/network failure") + "_simulate": "silent_fail" -> send "succeeds" but nothing ever arrives + "_simulate": "partial_fail" -> only the first OTP of N arrives + "_simulate": "content_mismatch" -> all arrive, but with corrupted content + absent / "ok" -> everything arrives correctly +""" + +from __future__ import annotations + +from dataclasses import dataclass, field + + +class AuthError(Exception): + """Credentials were rejected outright โ SRS FR-7 "auth rejected".""" + + +class ConnectionFailure(Exception): + """Couldn't reach the server at all โ SRS FR-7 "connection/network failure".""" + + +@dataclass +class DeliveredMessage: + to_addr: str + subject: str + body: str + attachments: list = field(default_factory=list) + inline_images: list = field(default_factory=list) + headers: dict = field(default_factory=dict) + + +@dataclass +class MockInbox: + """Stands in for M8ion's own test mailbox. Messages land here only when MockMailer + actually "delivers" them โ a silent-failure simulation means nothing shows up here + at all, exactly like a real dropped send would look from the receiving side.""" + + messages: list[DeliveredMessage] = field(default_factory=list) + + def messages_to(self, to_addr: str) -> list[DeliveredMessage]: + return [m for m in self.messages if m.to_addr == to_addr] + + def clear(self) -> None: + self.messages.clear() + + +class MockMailer: + """One instance represents one outbound connection attempt using a given set of + mailbox credentials. `inbox` is where successful sends land.""" + + def __init__(self, credentials: dict, inbox: MockInbox): + simulate = credentials.get("_simulate", "ok") + if simulate == "auth_fail": + raise AuthError("Authentication rejected for the supplied credentials") + if simulate == "connection_fail": + raise ConnectionFailure("Could not reach the mail server") + self._simulate = simulate + self.inbox = inbox + self._sent_count = 0 + + def configure(self, from_name: str = "", reply_to: str = "", save_sent_copy: bool = True) -> None: + self.from_name, self.reply_to, self.save_sent_copy = from_name, reply_to, save_sent_copy + + def send(self, to_addr: str, subject: str, body: str, attachments=None, inline_images=None, headers=None) -> None: + self._sent_count += 1 + + if self._simulate == "silent_fail": + return # "accepted" by the caller's mental model, but never arrives anywhere + + if self._simulate == "partial_fail" and self._sent_count > 1: + return # only the first message of a batch ever arrives + + if self._simulate == "content_mismatch": + body = f"CORRUPTED::{body}" + + self.inbox.messages.append(DeliveredMessage( + to_addr=to_addr, subject=subject, body=body, + attachments=list(attachments or []), inline_images=list(inline_images or []), headers=dict(headers or {}), + )) diff --git a/backend/normalize.py b/backend/normalize.py new file mode 100644 index 0000000000000000000000000000000000000000..906742a26f731be57d4685a5d021ee4b10e73b63 --- /dev/null +++ b/backend/normalize.py @@ -0,0 +1,175 @@ +""" +Practical, honest normalization โ not a textbook-complete 5NF engine (see the plan's +"feasibility note": BCNF/4NF/5NF require detecting multi-valued/join dependencies, which has +no safe general algorithm for arbitrary real-world data). What this module actually does: + +- 1NF: handled at classification time (backend/databases.py splits delimiter-separated values + only in columns classified as "tag" โ the one column type where a multi-value cell is + expected by design, not a guess). +- 2NF/3NF: real, mechanical functional-dependency discovery (a determinant column whose every + distinct value maps to exactly one value of another column, and which isn't itself a + candidate key) โ automatically extracted into a natural-keyed lookup table. +- Beyond 3NF: only ever *suggested* (a plain-language reason attached), never auto-applied โ + a composite pair of columns that together determine a third is flagged, not restructured. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field + + +@dataclass +class NormalizedTable: + name: str + columns: list[str] + rows: list[dict] + + +@dataclass +class NormalizationResult: + root: NormalizedTable + lookups: list[NormalizedTable] = field(default_factory=list) + suggestions: list[str] = field(default_factory=list) + + +def _distinct_count(rows: list[dict], col: str) -> int: + return len({row.get(col) for row in rows}) + + +def discover_functional_dependencies( + rows: list[dict], headers: list[str], exclude_determinants: set[str] = frozenset(), +) -> dict[str, set[str]]: + """{determinant: {columns it functionally determines}}. A column only qualifies as a + determinant if it has fewer distinct values than there are rows (otherwise it's a + candidate key, not a useful grouping column), more than one distinct value (otherwise + it's constant and splitting on it is meaningless), and isn't in `exclude_determinants` โ + a per-row identity column (an email address) can look like a "determinant" purely because + duplicate rows collapse its distinct count, which isn't a real grouping dimension; it's + still fine for such a column to be a *dependent* of something else.""" + n = len(rows) + deps: dict[str, set[str]] = {} + if n < 2: + return deps + + for a in headers: + if a in exclude_determinants: + continue + distinct_a = _distinct_count(rows, a) + if distinct_a >= n or distinct_a <= 1: + continue + for b in headers: + if a == b: + continue + mapping: dict[object, object] = {} + consistent = True + for row in rows: + va, vb = row.get(a), row.get(b) + if va in mapping and mapping[va] != vb: + consistent = False + break + mapping[va] = vb + if consistent: + deps.setdefault(a, set()).add(b) + return deps + + +def normalize( + rows: list[dict], headers: list[str], root_name: str = "root", exclude_determinants: set[str] = frozenset(), + auto_split: bool = True, +) -> NormalizationResult: + """Splits out one lookup table per determinant column (first-match-wins: once a column's + dependents are extracted, it isn't reconsidered as a dependent of a later determinant, to + avoid conflicting/overlapping splits), then scans what's left for a composite-determinant + signal worth flagging but not acting on. `exclude_determinants` โ see + discover_functional_dependencies โ keeps identity-like columns (email) from being treated + as a grouping dimension. + + auto_split=False keeps every column in the one table and reports nothing. Uploads use that: + "A determines B" found in a few hundred rows is usually coincidence (names are nearly unique), + and moving real columns out of the sheet because of it hid people's data from them.""" + if auto_split is False: + return NormalizationResult( + root=NormalizedTable(name=root_name, columns=list(headers), rows=[{c: r.get(c) for c in headers} for r in rows]), + ) + deps = discover_functional_dependencies(rows, headers, exclude_determinants) + + extracted_as_dependent: set[str] = set() + used_as_determinant: set[str] = set() + lookups: list[NormalizedTable] = [] + for determinant, dependents in deps.items(): + # A column already folded into another table as a dependent can't turn around and + # become a determinant itself โ and a two-way dependency (A<->B, common whenever both + # sides happen to have the same distinct-value count, e.g. company <-> company_city) + # would otherwise get extracted TWICE, once from each direction, stripping both + # columns out of root instead of just one. + if determinant in extracted_as_dependent: + continue + dependents = { + d for d in dependents + if d not in extracted_as_dependent and d not in used_as_determinant and d != determinant + } + if not dependents: + continue + lookup_cols = [determinant, *sorted(dependents)] + seen_keys: set[object] = set() + lookup_rows = [] + for row in rows: + key = row.get(determinant) + if key in seen_keys: + continue + seen_keys.add(key) + lookup_rows.append({c: row.get(c) for c in lookup_cols}) + lookups.append(NormalizedTable(name=f"{determinant}_lookup", columns=lookup_cols, rows=lookup_rows)) + used_as_determinant.add(determinant) + extracted_as_dependent.update(dependents) + + root_columns = [h for h in headers if h not in extracted_as_dependent] + root_rows = [{c: row.get(c) for c in root_columns} for row in rows] + + suggestions = _composite_dependency_suggestions(rows, root_columns, exclude_determinants) + + return NormalizationResult( + root=NormalizedTable(name=root_name, columns=root_columns, rows=root_rows), + lookups=lookups, + suggestions=suggestions, + ) + + +def _composite_dependency_suggestions( + rows: list[dict], headers: list[str], exclude_determinants: set[str] = frozenset(), +) -> list[str]: + """A bounded (O(columns^2)) scan for pairs (a, b) that together determine a third column + c, where neither a nor b alone does โ a BCNF/4NF-flavored signal. Reported as plain- + language text for a human to accept, never auto-applied.""" + n = len(rows) + if n < 3: + return [] + single_deps = discover_functional_dependencies(rows, headers, exclude_determinants) + suggestions: list[str] = [] + candidate_headers = [h for h in headers if h not in exclude_determinants] + + for i, a in enumerate(candidate_headers): + for b in candidate_headers[i + 1 :]: + pair_values = {(row.get(a), row.get(b)) for row in rows} + if len(pair_values) >= n: + continue # (a, b) together are already unique per row โ not a useful grouping + for c in headers: + if c in (a, b): + continue + if c in single_deps.get(a, set()) or c in single_deps.get(b, set()): + continue # already explained by a single-column dependency + mapping: dict[tuple, object] = {} + consistent = True + for row in rows: + key = (row.get(a), row.get(b)) + vc = row.get(c) + if key in mapping and mapping[key] != vc: + consistent = False + break + mapping[key] = vc + if consistent and len(mapping) < n: + suggestions.append( + f"Columns '{a}' and '{b}' together always determine '{c}' โ " + f"consider extracting a lookup table (not applied automatically)." + ) + return suggestions diff --git a/backend/orgs.py b/backend/orgs.py new file mode 100644 index 0000000000000000000000000000000000000000..89c8472257aaf1b3429be71d434fe918fdf1581b --- /dev/null +++ b/backend/orgs.py @@ -0,0 +1,316 @@ +""" +The org/owner/role model โ the foundation everything else (mailbox connections, contacts, +messages, sends) is scoped by. See docs/blueprint/blueprint.md "Core entities" and +docs/product/srs.md FR-1 through FR-3. + +Firestore layout (see backend/firestore_client.py for the local/real seam): + orgs/{org_id} โ {name, owner_uid, created_at} + orgs/{org_id}/members/{uid} โ {role, added_at, email?} + orgs/{org_id}/roles/{key} โ {name, permissions} (an edited built-in role, or a + custom one; built-ins not stored use their defaults) + user_orgs/{uid} โ {org_ids: {org_id: role, ...}} (reverse index, + kept in sync on every membership write, so + "which orgs does this user belong to" doesn't + require scanning every org) + +One person (one Firebase uid) can own or belong to multiple orgs โ the reverse index is +what makes that lookup cheap. +""" + +from __future__ import annotations + +import uuid +from datetime import datetime, timezone + +from backend import firestore_client as db +from backend.core.constants import BUILTIN_ROLES, ORG_CREATOR_ROLE, PERMISSIONS, ROLE_ALIASES, ROLE_RANK, ROLE_SPACES, SPACES + + +class PermissionError_(Exception): + """Raised when an actor's role doesn't meet the required rank for an action.""" + + +class NotFoundError(Exception): + """Raised when an org or membership doesn't exist.""" + + +def _now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def _member_path(org_id: str, uid: str) -> str: + return f"orgs/{org_id}/members/{uid}" + + +def _members_prefix(org_id: str) -> str: + return f"orgs/{org_id}/members/" + + +def _user_orgs_path(uid: str) -> str: + return f"user_orgs/{uid}" + + +def _set_reverse_index(uid: str, org_id: str, role: str) -> None: + doc = db.get_doc(_user_orgs_path(uid)) or {"org_ids": {}} + doc["org_ids"][org_id] = role + db.set_doc(_user_orgs_path(uid), doc) + + +def _clear_reverse_index(uid: str, org_id: str) -> None: + doc = db.get_doc(_user_orgs_path(uid)) + if doc and org_id in doc.get("org_ids", {}): + del doc["org_ids"][org_id] + db.set_doc(_user_orgs_path(uid), doc) + + +def create_org(owner_uid: str, name: str, kind: str | None = None) -> str: + """Creates a new org with `owner_uid` as its owner. Returns the new org_id. A single + uid can own โ and separately create โ more than one org (SRS note under FR-2). + `kind` is "personal" for an individual's own org (see backend/accounts.py).""" + org_id = uuid.uuid4().hex + doc = {"name": name, "owner_uid": owner_uid, "created_at": _now()} + if kind: + doc["kind"] = kind + db.set_doc(f"orgs/{org_id}", doc) + db.set_doc(_member_path(org_id, owner_uid), {"role": ORG_CREATOR_ROLE, "added_at": _now()}) + _set_reverse_index(owner_uid, org_id, ORG_CREATOR_ROLE) + return org_id + + +def get_org(org_id: str) -> dict: + org = db.get_doc(f"orgs/{org_id}") + if org is None: + raise NotFoundError(f"No org {org_id!r}") + return org + + +def get_role(org_id: str, uid: str) -> str | None: + """The uid's role in this org, or None if they aren't a member.""" + membership = db.get_doc(_member_path(org_id, uid)) + return membership["role"] if membership else None + + +def require_role(org_id: str, uid: str, minimum_role: str) -> str: + """Raises PermissionError_ unless uid's role in org_id ranks at or above + minimum_role. Returns the actor's actual role on success. Kept for rank checks between + built-in roles; feature checks use require_permission. Custom roles rank lowest.""" + role = get_role(org_id, uid) + if role is None: + raise PermissionError_(f"{uid!r} is not a member of org {org_id!r}") + if ROLE_RANK.get(role, 0) < ROLE_RANK[minimum_role]: + raise PermissionError_( + f"{uid!r} has role {role!r} in org {org_id!r}, needs at least {minimum_role!r}" + ) + return role + + +def _role_path(org_id: str, key: str) -> str: + return f"orgs/{org_id}/roles/{key}" + + +def list_roles(org_id: str) -> list[dict]: + """Every role in the org: the built-ins (with any edits) first, then custom ones.""" + prefix = f"orgs/{org_id}/roles/" + stored = {path[len(prefix):]: data for path, data in db.query_prefix(prefix).items()} + roles = [] + for key, default in BUILTIN_ROLES.items(): + data = default if key == ORG_CREATOR_ROLE else stored.get(key, default) + roles.append({"key": key, "name": default["name"], "permissions": list(data["permissions"]), "builtin": True}) + for key, data in sorted(stored.items(), key=lambda kv: kv[1].get("name", "").lower()): + if key not in BUILTIN_ROLES: + roles.append({"key": key, "name": data["name"], "permissions": list(data["permissions"]), "builtin": False}) + return roles + + +def permissions_for(org_id: str, role: str) -> set[str]: + role = ROLE_ALIASES.get(role, role) + if role == ORG_CREATOR_ROLE: + return set(PERMISSIONS) + stored = db.get_doc(_role_path(org_id, role)) + if stored is not None: + return set(stored["permissions"]) + return set(BUILTIN_ROLES.get(role, {"permissions": []})["permissions"]) + + +def require_permission(org_id: str, uid: str, permission: str | None = None) -> str: + """Raises PermissionError_ unless uid is a member of org_id whose role allows + `permission` (None: being a member is enough). Returns the actor's role.""" + role = get_role(org_id, uid) + if role is None: + raise PermissionError_(f"{uid!r} is not a member of org {org_id!r}") + if permission is not None and permission not in effective_permissions(org_id, uid): + raise PermissionError_(f"Your role doesn't allow this ({PERMISSIONS[permission].lower()})") + return role + + +def extra_roles_of(org_id: str, uid: str) -> list[str]: + doc = db.get_doc(_member_path(org_id, uid)) or {} + return list(doc.get("extra_roles", [])) + + +def all_roles_of(org_id: str, uid: str) -> list[str]: + """The main role first, then any extra roles. Someone can hold several.""" + role = get_role(org_id, uid) + return [role, *extra_roles_of(org_id, uid)] if role else [] + + +def effective_permissions(org_id: str, uid: str) -> set[str]: + out: set[str] = set() + for role in all_roles_of(org_id, uid): + out |= permissions_for(org_id, role) + return out + + +def spaces_for(org_id: str, uid: str) -> list[dict]: + """Every area, each marked allowed or not for this member.""" + opened: set[str] = set() + for role in all_roles_of(org_id, uid): + opened |= set(ROLE_SPACES.get(ROLE_ALIASES.get(role, role), [])) + return [{"key": k, "label": v[0], "about": v[1], "allowed": k in opened} for k, v in SPACES.items()] + + +def set_extra_roles(org_id: str, actor_uid: str, target_uid: str, roles: list[str]) -> None: + """Gives a member further roles beside their main one. Same rules as changing a role.""" + _check_manage(org_id, actor_uid, target_uid) + roles = [r for r in dict.fromkeys(roles)] + for role in roles: + _check_grant(org_id, actor_uid, role) + doc = db.get_doc(_member_path(org_id, target_uid)) + doc["extra_roles"] = [r for r in roles if r != doc["role"]] + db.set_doc(_member_path(org_id, target_uid), doc) + + +def _role_exists(org_id: str, role: str) -> bool: + return role in BUILTIN_ROLES or role in ROLE_ALIASES or db.get_doc(_role_path(org_id, role)) is not None + + +def _check_grant(org_id: str, actor_uid: str, role: str) -> str: + """The checks shared by inviting, adding and changing someone's role. Nobody can hand + out ownership, only an owner can hand out admin, and nobody can hand out more than + they can do themselves.""" + if role == ORG_CREATOR_ROLE: + raise PermissionError_("Ownership can't be granted โ only by creating the org") + if not _role_exists(org_id, role): + raise ValueError(f"Unknown role {role!r}") + actor_role = require_permission(org_id, actor_uid, "manage_team") + if ROLE_ALIASES.get(role, role) == "admin" and actor_role != ORG_CREATOR_ROLE: + raise PermissionError_("Only an owner can make someone an admin") + if not permissions_for(org_id, role) <= permissions_for(org_id, actor_role): + raise PermissionError_("You can't give someone more access than you have") + return actor_role + + +def _check_manage(org_id: str, actor_uid: str, target_uid: str) -> str: + """Checks before changing or removing an existing member. Returns their role.""" + target_role = get_role(org_id, target_uid) + if target_role is None: + raise NotFoundError(f"{target_uid!r} is not a member of org {org_id!r}") + if target_role == ORG_CREATOR_ROLE: + raise PermissionError_("The owner can't be changed or removed") + actor_role = require_permission(org_id, actor_uid, "manage_team") + if target_role == "admin" and actor_role != ORG_CREATOR_ROLE: + raise PermissionError_("Only an owner can change or remove an admin") + return target_role + + +def add_member(org_id: str, actor_uid: str, target_uid: str, role: str, email: str = "") -> None: + """actor_uid adds target_uid to org_id with the given role (see _check_grant).""" + _check_grant(org_id, actor_uid, role) + doc = {"role": role, "added_at": _now()} + if email: + doc["email"] = email + db.set_doc(_member_path(org_id, target_uid), doc) + _set_reverse_index(target_uid, org_id, role) + + +def join(org_id: str, uid: str, role: str, email: str = "") -> None: + """Adds uid with an already-approved role (an accepted invite). Never lowers or + replaces the role of someone who is already a member.""" + if get_role(org_id, uid) is not None: + return + doc = {"role": role, "added_at": _now()} + if email: + doc["email"] = email + db.set_doc(_member_path(org_id, uid), doc) + _set_reverse_index(uid, org_id, role) + + +def change_member_role(org_id: str, actor_uid: str, target_uid: str, role: str) -> None: + _check_manage(org_id, actor_uid, target_uid) + _check_grant(org_id, actor_uid, role) + doc = db.get_doc(_member_path(org_id, target_uid)) + doc["role"] = role + db.set_doc(_member_path(org_id, target_uid), doc) + _set_reverse_index(target_uid, org_id, role) + + +def remove_member(org_id: str, actor_uid: str, target_uid: str) -> None: + """Someone who can manage the team can remove anyone except the owner; only an + owner can remove an admin.""" + _check_manage(org_id, actor_uid, target_uid) + db.delete_doc(_member_path(org_id, target_uid)) + _clear_reverse_index(target_uid, org_id) + + +def leave(org_id: str, uid: str) -> None: + """A member leaves on their own. The owner can't leave their own org.""" + role = require_permission(org_id, uid) + if role == ORG_CREATOR_ROLE: + raise PermissionError_("The owner can't leave their own organisation") + db.delete_doc(_member_path(org_id, uid)) + _clear_reverse_index(uid, org_id) + + +def save_role(org_id: str, actor_uid: str, key: str | None, name: str, permissions: list[str]) -> str: + """Creates a custom role (key None) or edits one, built-ins included except Owner. + Returns the role's key.""" + actor_role = require_permission(org_id, actor_uid, "manage_team") + unknown = [p for p in permissions if p not in PERMISSIONS] + if unknown: + raise ValueError(f"Unknown permission {unknown[0]!r}") + if not set(permissions) <= permissions_for(org_id, actor_role): + raise PermissionError_("You can't give a role more access than you have") + if key == ORG_CREATOR_ROLE: + raise PermissionError_("The Owner role can't be changed") + if key is None: + name = (name or "").strip() + if not name or len(name) > 40: + raise ValueError("Give the role a name of up to 40 characters") + if any(r["name"].lower() == name.lower() for r in list_roles(org_id)): + raise ValueError(f"There is already a role called {name!r}") + key = "custom-" + uuid.uuid4().hex[:10] + elif not _role_exists(org_id, key): + raise NotFoundError(f"No role {key!r}") + if key in BUILTIN_ROLES: + name = BUILTIN_ROLES[key]["name"] + if key == "admin" and actor_role != ORG_CREATOR_ROLE: + raise PermissionError_("Only an owner can change the Admin role") + else: + stored = db.get_doc(_role_path(org_id, key)) + name = (name or "").strip() or (stored or {}).get("name", "") + db.set_doc(_role_path(org_id, key), {"name": name, "permissions": sorted(set(permissions))}) + return key + + +def delete_role(org_id: str, actor_uid: str, key: str) -> None: + """Removes a custom role nobody holds, or resets an edited built-in to its default.""" + require_permission(org_id, actor_uid, "manage_team") + if key == ORG_CREATOR_ROLE: + raise PermissionError_("The Owner role can't be changed") + if key not in BUILTIN_ROLES: + if any(m["role"] == key for m in list_members(org_id).values()): + raise ValueError("Move everyone off this role before deleting it") + db.delete_doc(_role_path(org_id, key)) + + +def list_members(org_id: str) -> dict[str, dict]: + """{uid: {role, added_at}} for every member of org_id.""" + prefix = _members_prefix(org_id) + docs = db.query_prefix(prefix) + return {path[len(prefix):]: data for path, data in docs.items()} + + +def list_orgs_for_user(uid: str) -> dict[str, str]: + """{org_id: role} for every org this uid belongs to, across all their orgs.""" + doc = db.get_doc(_user_orgs_path(uid)) + return dict(doc["org_ids"]) if doc else {} diff --git a/backend/overview.py b/backend/overview.py new file mode 100644 index 0000000000000000000000000000000000000000..a564c6a43d2795c2bbf4e28b44f2c5413fd70f67 --- /dev/null +++ b/backend/overview.py @@ -0,0 +1,89 @@ +""" +The dashboard's numbers in one call: lists and people, mailboxes and their health, recent +sends and how they went, forms and presets. Read-only, and every count comes from the same +stores the other pages read, so the dashboard never disagrees with them. +""" + +from __future__ import annotations + +from datetime import datetime, timedelta, timezone + +from backend import brands, collect, databases, mailboxes, orgs, presets, sending, workbook + +_RECENT_DAYS = 30 + + +def _parse(ts: str | None) -> datetime | None: + if not ts: + return None + try: + return datetime.fromisoformat(ts) + except ValueError: + return None + + +def get_overview(org_id: str, actor_uid: str) -> dict: + orgs.require_permission(org_id, actor_uid) + + lists = [{"database_id": did, **d} for did, d in databases.list_databases(org_id).items()] + boxes = list(mailboxes.list_mailboxes(org_id).values()) + sends = sending.list_sends(org_id, actor_uid, limit=500) + forms = [k for k in collect.list_keys(org_id, actor_uid) if not k.get("revoked")] + saved_presets = presets.list_presets(org_id, actor_uid) + + cutoff = datetime.now(timezone.utc) - timedelta(days=_RECENT_DAYS) + recent = [s for s in sends if (_parse(s["sent_at"]) or cutoff) > cutoff] + delivered = sum(s["sent"] for s in recent) + failed = sum(s["failed"] for s in recent) + + # One point per day for the last 30 days, oldest first, for the activity chart. + by_day: dict[str, int] = {} + for s in recent: + day = (_parse(s["sent_at"]) or cutoff).date().isoformat() + by_day[day] = by_day.get(day, 0) + s["sent"] + today = datetime.now(timezone.utc).date() + activity = [ + {"day": (today - timedelta(days=i)).isoformat(), "sent": by_day.get((today - timedelta(days=i)).isoformat(), 0)} + for i in range(_RECENT_DAYS - 1, -1, -1) + ] + + names = {d["database_id"]: d["name"] for d in lists} + # With a main sheet, people are counted once each and the "lists" are its audiences (their + # stored counts, so this stays one cheap read). Without one, the old separate sheets. + main = next((d for d in lists if d.get("is_main")), None) + conflicts = 0 + if main: + audiences = workbook._audience_docs(org_id) + people = main.get("row_count", 0) + largest = sorted( + ({"database_id": aid, "name": a["name"], "row_count": a.get("count", 0), "audience": True} for aid, a in audiences.items()), + key=lambda d: d["row_count"], reverse=True, + )[:5] + list_count = len(audiences) + conflicts = main.get("open_conflicts", 0) + else: + live = [d for d in lists if not d.get("archived")] + people = sum(d.get("row_count", 0) for d in live if not d.get("disabled")) + largest = sorted( + ({"database_id": d["database_id"], "name": d["name"], "row_count": d.get("row_count", 0)} for d in live), + key=lambda d: d["row_count"], reverse=True, + )[:5] + list_count = len(live) + return { + "people": people, + "lists": list_count, + "mailboxes": { + "total": len(boxes), + "verified": sum(1 for b in boxes if b.get("status") == "verified"), + "needs_attention": sum(1 for b in boxes if b.get("status") not in ("verified", "pending_verification") and not b.get("dismissed")), + }, + "sends_30d": {"campaigns": len(recent), "delivered": delivered, "failed": failed}, + "forms": len(forms), + "presets": len(saved_presets), + "activity": activity, + "recent_sends": [s | {"list_name": names.get(s["database_id"], "Deleted list")} for s in sends[:8]], + "largest_lists": largest, + "audience_conflicts": conflicts, + "brands": len(brands.list_brands(org_id)), + "custom_roles": sum(1 for r in orgs.list_roles(org_id) if not r["builtin"]), + } diff --git a/backend/presets.py b/backend/presets.py new file mode 100644 index 0000000000000000000000000000000000000000..c768c9656be386e6d54e9c6be1e36dcc3826a12c --- /dev/null +++ b/backend/presets.py @@ -0,0 +1,83 @@ +""" +Saved email presets: a whole message (subject plus either a drag-and-drop design or raw HTML) +that a sender can start the next campaign from. Built-in starter layouts live in the frontend; +only the ones a sender saves are stored, per org at orgs/{org_id}/presets/{id}. +""" + +from __future__ import annotations + +import json +import uuid +from datetime import datetime, timezone + +from backend import firestore_client as db +from backend import orgs + +_MAX_NAME = 80 +_MAX_SUBJECT = 300 +# A stored document must stay under Firestore's 1 MB limit, images included. +_MAX_CONTENT_BYTES = 900_000 +_MODES = ("builder", "html") + + +def _now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def _prefix(org_id: str) -> str: + return f"orgs/{org_id}/presets/" + + +def _path(org_id: str, preset_id: str) -> str: + return f"{_prefix(org_id)}{preset_id}" + + +def _clean(name: str, subject: str, mode: str, design: dict | None, html: str) -> dict: + name = name.strip() + if not name or len(name) > _MAX_NAME: + raise ValueError(f"Give the preset a name of at most {_MAX_NAME} characters") + if len(subject) > _MAX_SUBJECT: + raise ValueError("The subject is too long") + if mode not in _MODES: + raise ValueError("A preset is either a drag-and-drop design or HTML") + if mode == "builder" and not isinstance(design, dict): + raise ValueError("This preset has no design to save") + size = len(json.dumps(design or {})) + len(html.encode()) + if size > _MAX_CONTENT_BYTES: + raise ValueError("This preset is too large to save. Use smaller images and try again") + return {"name": name, "subject": subject, "mode": mode, "design": design if mode == "builder" else None, "html": html} + + +def create_preset(org_id: str, actor_uid: str, name: str, subject: str, mode: str, design: dict | None, html: str) -> str: + orgs.require_permission(org_id, actor_uid, "edit_emails") + data = _clean(name, subject, mode, design, html) + preset_id = uuid.uuid4().hex + db.set_doc(_path(org_id, preset_id), data | {"created_at": _now(), "updated_at": _now()}) + return preset_id + + +def update_preset(org_id: str, actor_uid: str, preset_id: str, name: str, subject: str, mode: str, + design: dict | None, html: str) -> None: + orgs.require_permission(org_id, actor_uid, "edit_emails") + get_preset(org_id, preset_id) + db.update_doc(_path(org_id, preset_id), _clean(name, subject, mode, design, html) | {"updated_at": _now()}) + + +def delete_preset(org_id: str, actor_uid: str, preset_id: str) -> None: + orgs.require_permission(org_id, actor_uid, "edit_emails") + get_preset(org_id, preset_id) + db.delete_doc(_path(org_id, preset_id)) + + +def get_preset(org_id: str, preset_id: str) -> dict: + doc = db.get_doc(_path(org_id, preset_id)) + if doc is None: + raise orgs.NotFoundError(f"No preset {preset_id!r} in org {org_id!r}") + return doc + + +def list_presets(org_id: str, actor_uid: str) -> list[dict]: + orgs.require_permission(org_id, actor_uid) + prefix = _prefix(org_id) + items = [data | {"preset_id": path[len(prefix):]} for path, data in db.query_prefix(prefix).items()] + return sorted(items, key=lambda p: p.get("updated_at", ""), reverse=True) diff --git a/backend/rate_limiter.py b/backend/rate_limiter.py new file mode 100644 index 0000000000000000000000000000000000000000..38eb2a4206a30b790c184bfec53e3a8fcf604a62 --- /dev/null +++ b/backend/rate_limiter.py @@ -0,0 +1,78 @@ +""" +Basic per-org hourly send cap (docs/blueprint/adr/0004, blueprint "Rate limiting"). Phase 1 +scope only: a rolling window enforced server-side. Anomaly detection and the 4-stage +escalation (detect -> block -> silently_report -> auto_temporary_ban) are Phase 2 +(docs/product/checklist.md) โ this module only ever does stage one, "detect (and block)". + +Rolling, not fixed-hour-boundary, per ADR-0004 โ avoids the burst-at-the-top-of-the-hour +gap a naive reset would allow. Recorded timestamps live in the local store now; the +blueprint's eventual home for this is Redis/Memorystore, not Firestore (same reasoning as +the old due-job queue: don't put a perpetually-touched counter in a serverless-priced store). +""" + +from __future__ import annotations + +import time + +from backend import local_store +from backend.core.constants import DEFAULT_HOURLY_SEND_CAP + +_WINDOW_SECONDS = 3600 + + +class RateLimitExceeded(Exception): + def __init__(self, org_id: str, requested: int, remaining: int): + self.org_id = org_id + self.requested = requested + self.remaining = remaining + super().__init__( + f"org {org_id!r} requested {requested} sends but only {remaining} remain " + f"in the current rolling hour" + ) + + +def _counter_path(org_id: str) -> str: + return f"rate_counters/{org_id}" + + +def _current_timestamps(org_id: str, now: float) -> list[float]: + doc = local_store.get_doc(_counter_path(org_id)) + timestamps = doc["timestamps"] if doc else [] + return [t for t in timestamps if now - t < _WINDOW_SECONDS] + + +def remaining_capacity(org_id: str, hourly_cap: int = DEFAULT_HOURLY_SEND_CAP) -> int: + now = time.time() + used = len(_current_timestamps(org_id, now)) + return max(0, hourly_cap - used) + + +def check_and_consume(org_id: str, count: int, hourly_cap: int = DEFAULT_HOURLY_SEND_CAP) -> None: + """Reserves `count` sends against org_id's rolling-hour cap, all at once โ a batch + either entirely fits or the whole call is rejected (Phase 1 simplification: no partial + sends within a single batch). Raises RateLimitExceeded if it doesn't fit. Server-side + only โ nothing here is ever populated from a client-supplied value.""" + now = time.time() + timestamps = _current_timestamps(org_id, now) + remaining = max(0, hourly_cap - len(timestamps)) + if count > remaining: + raise RateLimitExceeded(org_id, count, remaining) + + timestamps.extend([now] * count) + local_store.set_doc(_counter_path(org_id), {"timestamps": timestamps}) + + +def allow_hit(bucket: str, limit: int, window_seconds: int) -> bool: + """Generic rolling-window counter for anything that is not an org send (e.g. the public + collection endpoint's per-key / per-IP / per-address limits). Records the hit and returns + True if it is within `limit` hits per `window_seconds`; returns False (and records + nothing) if it would exceed the limit. Always the local store, never Firestore.""" + now = time.time() + path = f"rate_buckets/{bucket}" + doc = local_store.get_doc(path) + hits = [t for t in (doc["timestamps"] if doc else []) if now - t < window_seconds] + if len(hits) >= limit: + return False + hits.append(now) + local_store.set_doc(path, {"timestamps": hits}) + return True diff --git a/backend/rename_suggest.py b/backend/rename_suggest.py new file mode 100644 index 0000000000000000000000000000000000000000..c5ab62dede7c2e019b5a3eda0f6b1042707844ac --- /dev/null +++ b/backend/rename_suggest.py @@ -0,0 +1,100 @@ +"""Suggests short, readable column names for headers that came from form questions or exports +("Phone Number (WhatsApp preferred)" -> "Phone"). Pure regex and string rules: no state, nothing +is renamed here. The caller shows the suggestion and the user accepts it.""" + +from __future__ import annotations + +import re + +# (pattern on the lowercased header, suggested name, reason). First match wins, so order matters. +_KNOWN: list[tuple[re.Pattern[str], str, str]] = [ + (re.compile(r"^(timestamp|submitted( at| on)?|submission (date|time)|date submitted)$"), "Submitted", "form timestamp"), + (re.compile(r"e-?mail"), "Email", "holds email addresses"), + (re.compile(r"date of birth|birth ?day|\bd\.?o\.?b\b"), "Date of birth", "date of birth"), + (re.compile(r"\bage\s*(range|group|bracket)\b|\bage\b"), "Age range", "age"), + (re.compile(r"\b(gender|sex)\b"), "Gender", "gender"), + (re.compile(r"hours?\s+(per|a|each)\s+week|weekly hours"), "Weekly hours", "hours per week"), + (re.compile(r"how did you (hear|know|find|get to know)|where did you (hear|find)|\breferr(ed by|al)\b|heard about"), "Heard about us", "referral question"), + (re.compile(r"join (the|our) .*(group|link|community|channel)|group link|invite link"), "Group link", "group invite"), + (re.compile(r"school|institution|universit|college|organi[sz]ation|company|employer|workplace"), "Organization", "where they study or work"), + (re.compile(r"\b(town|city)\b|residence|where do you live|\blocation\b"), "City", "where they live"), + (re.compile(r"current (status|occupation)|occupation|employment status"), "Status", "current status"), + (re.compile(r"phone|mobile|whats\s?app|\btel(ephone)?\b|contact (number|no)|cell"), "Phone", "phone number"), + (re.compile(r"^(full\s+|first\s+and\s+last\s+|your\s+|participant'?s?\s+|student'?s?\s+)?name\b"), "Name", "a person's name"), +] + +_PAREN = re.compile(r"\s*[\(\[][^)\]]*[\)\]]") +_LEAD = re.compile(r"^(please|kindly|enter|provide|state|type|what(?:'s| is| are)?|which|your|the)\s+", re.I) +_CLAUSE_SPLIT = re.compile(r"\s*(?:/|\||:| - |,|;| that | which | you | to )\s*") +_MAX_PLAIN = 28 + + +def _clean(header: str) -> str: + text = _PAREN.sub("", header).strip().rstrip("?.:! ") + for _ in range(3): + stripped = _LEAD.sub("", text) + if stripped == text: + break + text = stripped + text = _CLAUSE_SPLIT.split(text)[0].strip() or text + return text[:1].upper() + text[1:] if text else text + + +def _is_messy(header: str) -> bool: + return bool(_PAREN.search(header)) or "?" in header or len(header) > _MAX_PLAIN or "/" in header + + +def suggest_rename(header: str, column_type: str = "text", taken: set[str] | None = None) -> dict | None: + """Returns {"suggested", "reason"} or None. `taken` is the lowercase set of other column + names, so a suggestion never collides with one that exists.""" + taken = taken or set() + original = header.strip() + if not original: + return None + low = original.lower() + + suggestion: str | None = None + reason = "" + for pattern, name, why in _KNOWN: + if pattern.search(low): + suggestion, reason = name, why + break + + # A bare "Name" or "Phone" header is already fine; known rules only fire when the header + # is long, wrapped in brackets, a question, or not already the short name. + if suggestion and original.lower() == suggestion.lower(): + return None + if suggestion and not _is_messy(original) and len(original) <= len(suggestion) + 4: + return None + + if suggestion is None: + if not _is_messy(original): + return None + cleaned = _clean(original) + if cleaned and len(cleaned) <= _MAX_PLAIN and cleaned.lower() != low: + suggestion, reason = cleaned, "shorter wording" + elif column_type == "email": + suggestion, reason = "Email", "holds email addresses" + elif column_type == "contact": + suggestion, reason = "Phone", "holds phone numbers" + else: + return None + + if suggestion.lower() == low or suggestion.lower() in taken: + return None + return {"suggested": suggestion, "reason": reason} + + +def suggest_renames(columns: list[dict]) -> list[dict]: + """One suggestion per column that has one, each avoiding names already used by other columns + and by earlier suggestions.""" + names = {c["name"].lower() for c in columns} + claimed: set[str] = set() + out: list[dict] = [] + for col in columns: + taken = (names - {col["name"].lower()}) | claimed + hit = suggest_rename(col["name"], col.get("type", "text"), taken) + if hit: + claimed.add(hit["suggested"].lower()) + out.append({"column": col["name"], **hit}) + return out diff --git a/backend/sending.py b/backend/sending.py new file mode 100644 index 0000000000000000000000000000000000000000..507b9b5f69d0130000d83a6ed085e91d11c3775a --- /dev/null +++ b/backend/sending.py @@ -0,0 +1,713 @@ +""" +Manual send โ the Phase 1 slice of docs/blueprint/blueprint.md "Sending pipeline". Every +send is tracked per-recipient (SRS FR-18), never only per-broadcast โ this is also what +billing (per-recipient, ADR-0005) and rate limiting (per-send, not per-batch) both read +from. + +Scheduled sends and bounce/DSN detection (SRS FR-19/20) are Phase 2 โ this module only +covers a synchronous, immediate, manual send (a "Campaign" in the frontend's terms โ see +frontend/src/pages/Campaigns.tsx โ not yet an automation), which is enough to prove +per-recipient status tracking end-to-end. Which mailer actually does the sending (mock vs. +real SMTP) is decided by backend/mailer_client.py's REAL_SEND_ENABLED flag, not by anything +in this file. + +Recipients come from backend/databases.py (a database's rows), not a flat contact list โ each +row's own column values are substituted into {Placeholder} tokens in the subject/body before +that recipient's copy is sent, via substitute_placeholders. +""" + +from __future__ import annotations + +import base64 +import logging +import threading +import os +import time +import uuid +from concurrent.futures import ThreadPoolExecutor +from datetime import datetime, timezone + +from backend import brands, certificates, databases, delivery, email_parts, firestore_client as db, mailboxes, mailer_client, messages, orgs, rate_limiter, settings, templating, unsubscribe, workbook +from backend.mock_mailer import AuthError, ConnectionFailure + +log = logging.getLogger(__name__) + +def _now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def _send_path(org_id: str, send_id: str) -> str: + return f"orgs/{org_id}/sends/{send_id}" + + +def substitute_placeholders(template: str, row: dict, columns: list[dict] | None = None, html: bool = False) -> str: + """Renders one recipient's copy of `template` (see backend/templating.py): {ColumnName} is + replaced by that row's value (blank if the row has none โ a gap for one row, not an error), + {Name|fallback} covers blanks, list columns become bullets or "A, B and C", and + {if ...}{else}{/if} blocks pick content by the row's values. With html=True, row values are + escaped so they cannot become markup.""" + return templating.render(template, row, columns, html=html) + + +def _template_problems(subject: str, html_body: str, columns: list[dict]) -> list[str]: + # Checked separately: a block opened in the subject must not be "closed" by the body. + return list(dict.fromkeys( + templating.validate_template(subject, columns) + templating.validate_template(html_body, columns) + )) + + +def preview_render( + org_id: str, database_id: str, subject: str, html_body: str, + segment: list[dict] | None = None, index: int = 0, email_column: str | None = None, +) -> dict: + """What recipient number `index` (of those the segment matches) would receive, using the + same renderer as the real send, plus any template problems that would block a send.""" + database = workbook.for_sending(org_id, database_id, databases.get_database(org_id, database_id)) + columns = database["columns"] + problems = _template_problems(subject, html_body, columns) + rows = _recipient_rows(org_id, database_id, database, segment, email_column) + email_column = _email_column(database, email_column) + if problems or not rows: + return {"subject": subject, "html_body": html_body, "problems": problems, "recipient": None} + row = rows[index % len(rows)] + return { + "subject": substitute_placeholders(subject, row, columns), + "html_body": substitute_placeholders(html_body, row, columns, html=True), + "problems": [], + "recipient": row.get(email_column) if email_column else None, + } + + +def _recipient_rows( + org_id: str, database_id: str, database: dict, segment: list[dict] | None, email_column: str | None = None, +) -> list[dict]: + """Who a send reaches: one row per address, the newest entry for anyone listed twice, then + narrowed by the segment's rules.""" + email_column = _email_column(database, email_column) + rows = workbook.latest_per_person(databases.list_rows(org_id, database_id), email_column) + if segment: + rows = databases.apply_segment(rows, database["columns"], segment) + return rows + + +def _certificates_for_organisations(org_id: str) -> None: + """Certificates are for organisation accounts. An individual's workspace is a personal org.""" + if orgs.get_org(org_id).get("kind") == "personal": + raise orgs.PermissionError_("Certificates are for organisation accounts") + + +def preview_certificate( + org_id: str, database_id: str, certificate: dict, segment: list[dict] | None = None, index: int = 0, + email_column: str | None = None, +) -> dict: + """The certificate recipient number `index` would get, as a scaled-down PNG, so the + composer shows the real generated file rather than an approximation.""" + _certificates_for_organisations(org_id) + spec = certificates.parse_spec(certificate) + database = workbook.for_sending(org_id, database_id, databases.get_database(org_id, database_id)) + email_column = _email_column(database, email_column) + rows = _recipient_rows(org_id, database_id, database, segment, email_column) + if rows: + row = rows[index % len(rows)] + text = certificates.text_for(spec, row, database["columns"]) + recipient = row.get(email_column) + else: + text, recipient = spec.text, None + return {"recipient": recipient, "text": text, "image_b64": base64.b64encode(certificates.preview_png(spec, text)).decode()} + + +def _email_column(database: dict, chosen: str | None = None) -> str | None: + """The column whose addresses are sent to: `chosen` when given (a list can hold more than + one email column, such as a guest's address and the staff member who checked them in), + otherwise the first email column.""" + emails = [col["name"] for col in database["columns"] if col["type"] == "email"] + if chosen: + if chosen not in emails: + raise ValueError(f"{chosen!r} is not an email column in this list") + return chosen + return emails[0] if emails else None + + +ACTIVE = ("queued", "sending") +_locks: dict[tuple[str, str], threading.Lock] = {} +_WORKER = uuid.uuid4().hex[:12] # names this server when it holds a send's lease +# Sends run in their own small pool, so the threads that answer pages are never all busy +# sending. Sends beyond the pool wait their turn; they are saved as queued, so nothing is lost. +_POOL = ThreadPoolExecutor(max_workers=6, thread_name_prefix="send") + + +def sends_here() -> bool: + """False on a server that cannot reach mail servers (the Hugging Face Space). Sends then stay + queued and the sending worker on another machine delivers them (python -m backend.worker).""" + return os.getenv("SEND_ON_THIS_SERVER", "true").lower() != "false" + + +WORKER_DOC = "system/sending_worker" +WORKER_OFFLINE_AFTER = 900 # seconds without a check-in before the app warns (a 5-minute wait plus a long pass) + + +def worker_checked_in(now: datetime | None = None) -> None: + db.set_doc(WORKER_DOC, {"last_seen": (now or datetime.now(timezone.utc)).isoformat()}) + + +def sender_status(org_id: str, now: datetime | None = None) -> dict: + """Whether sends from this organisation are going out. Only a server that leaves sending to + the worker can be "offline"; the waiting count is this organisation's queued sends.""" + if sends_here(): + return {"online": True, "last_seen": None, "waiting": 0} + now = now or datetime.now(timezone.utc) + seen = (db.get_doc(WORKER_DOC) or {}).get("last_seen") + online = bool(seen) and (now - datetime.fromisoformat(seen)).total_seconds() < WORKER_OFFLINE_AFTER + waiting = sum(1 for d in db.query_prefix("active_sends/").values() if d.get("org_id") == org_id) + return {"online": online, "last_seen": seen, "waiting": waiting} + + +def start_send(org_id: str, send_id: str) -> None: + """Hands a queued send to the sending pool and returns at once.""" + if sends_here(): + _POOL.submit(process_send, org_id, send_id) + + +def start_job(fn, *args) -> None: + """Runs other sending work (API messages) in the same pool. Where this server cannot send, + the work waits for the worker (it is found again through its own queue).""" + if sends_here(): + _POOL.submit(fn, *args) + + +def _parse_when(value: str) -> datetime: + try: + when = datetime.fromisoformat(value.replace("Z", "+00:00")) + except (ValueError, AttributeError) as exc: + raise ValueError("That date and time could not be read") from exc + return when if when.tzinfo else when.replace(tzinfo=timezone.utc) + + +def clean_window(window: dict | None, default_timezone: str = "UTC") -> dict | None: + """A sending window: only send between `start` and `end` (HH:MM) on the given weekdays + (0 is Monday), in the given time zone. None means no restriction.""" + if not window: + return None + from zoneinfo import ZoneInfo + try: + start, end = str(window["start"]), str(window["end"]) + for value in (start, end): + datetime.strptime(value, "%H:%M") + days = sorted({int(d) for d in window.get("days", range(7))}) + zone = str(window.get("timezone") or default_timezone or "UTC") + ZoneInfo(zone) + except Exception as exc: + raise ValueError("The sending window is not valid") from exc + if start >= end: + raise ValueError("The sending window must end after it starts") + if not days or any(d < 0 or d > 6 for d in days): + raise ValueError("Choose at least one day for the sending window") + return {"start": start, "end": end, "days": days, "timezone": zone} + + +def _in_window(window: dict | None, now: datetime) -> bool: + if not window: + return True + from zoneinfo import ZoneInfo + local = now.astimezone(ZoneInfo(window["timezone"])) + return local.weekday() in window["days"] and window["start"] <= local.strftime("%H:%M") < window["end"] + + +def _payload_path(org_id: str, send_id: str) -> str: + return f"orgs/{org_id}/send_payloads/{send_id}" + + +def _active_path(org_id: str, send_id: str) -> str: + return f"active_sends/{org_id}__{send_id}" + + +def _set_active(org_id: str, send_id: str, active: bool) -> None: + if active: + db.set_doc(_active_path(org_id, send_id), {"org_id": org_id, "send_id": send_id}) + else: + db.delete_doc(_active_path(org_id, send_id)) + + +def send_campaign( + org_id: str, + actor_uid: str, + subject: str, + html_body: str, + mailbox_connection_id: str, + database_id: str, + segment: list[dict] | None = None, + attachments: list[dict] | None = None, + certificate: dict | None = None, + email_column: str | None = None, + mode: str | None = None, + design: dict | None = None, + scheduled_at: str | None = None, + window: dict | None = None, +) -> str: + """Queues the campaign and sends what can go now: `queue_campaign` followed by + `process_send`. A request handler calls queue_campaign and hands process_send to a + background task so the page does not wait; this does both in one go.""" + send_id = queue_campaign( + org_id, actor_uid, subject, html_body, mailbox_connection_id, database_id, segment, + attachments, certificate, email_column, mode, design, scheduled_at, window, + ) + process_send(org_id, send_id) + return send_id + + +def queue_campaign( + org_id: str, + actor_uid: str, + subject: str, + html_body: str, + mailbox_connection_id: str, + database_id: str, + segment: list[dict] | None = None, + attachments: list[dict] | None = None, + certificate: dict | None = None, + email_column: str | None = None, + mode: str | None = None, + design: dict | None = None, + scheduled_at: str | None = None, + window: dict | None = None, + only_row_ids: list[str] | None = None, + automated: bool = False, +) -> str: + """Saves a campaign to send to every row in `database_id` that has a value in its + email-typed column, substituting that row's own values into {Placeholder} tokens first. + `segment`, if given, is a list of {field, op, value} conditions (ANDed, see + databases.apply_segment) that narrows the recipient list before the email-column check โ + the same predicate the Campaigns page's live "N recipients" preview runs, so what you + previewed is exactly who gets sent to. Raises ValueError if the mailbox isn't verified or + the database has no column classified as "email" (set one via databases.update_column_type + first). + + `attachments` ([{filename, content_type, data_b64}]) go to every recipient as they are. + `certificate` (see backend/certificates.parse_spec) adds one generated file per recipient, + with that recipient's own values drawn onto the image. Images uploaded into the message + travel as inline parts (backend/email_parts.extract_inline_images). + + `scheduled_at` (an ISO date-time) holds the send until then; `window` limits sending to + certain hours and days (see clean_window). The send is carried out by process_send, which + keeps to the mailbox's daily limit and the organisation's hourly cap by sending what fits + and continuing when room opens up. + + `only_row_ids` narrows the send to those rows (a welcome email goes to the one new person). + `automated` is for mail the system sends on a member's earlier say-so, such as a form's + welcome email: no one is signed in then, so the permission check is skipped.""" + if not automated: + orgs.require_permission(org_id, actor_uid, "send") + if certificate: + _certificates_for_organisations(org_id) + + connection = mailboxes.get_mailbox(org_id, mailbox_connection_id) + if connection["status"] != "verified": + raise ValueError( + f"Mailbox connection {mailbox_connection_id!r} is {connection['status']!r}, " + f"not verified โ it can't be used to send" + ) + + database = workbook.for_sending(org_id, database_id, databases.get_database(org_id, database_id)) + email_column = _email_column(database, email_column) + if email_column is None: + raise ValueError( + f"Database {database_id!r} has no column classified as an email address โ " + f"set one via Manage columns before sending" + ) + + problems = _template_problems(subject, html_body, database["columns"]) + if problems: + raise ValueError("The message cannot be sent: " + "; ".join(problems)) + + # Checked now so a bad attachment or image fails the request, not the background send. + email_parts.decode_attachments(attachments) + spec = certificates.parse_spec(certificate) if certificate else None + email_parts.extract_inline_images(html_body) + + if scheduled_at: + scheduled_at = _parse_when(scheduled_at).isoformat() + window = clean_window(window, (orgs.get_org(org_id).get("timezone") or "UTC")) + + rows = _recipient_rows(org_id, database_id, database, segment, email_column) + if only_row_ids is not None: + rows = [r for r in rows if r["row_id"] in only_row_ids] + brand = brands.brand_for_mailbox(org_id, mailbox_connection_id) or {} + # The HTML as written (inline images still in place), so the details page shows it whole. + message_id = messages.create_message( + org_id, actor_uid, subject, html_body if len(html_body) <= 900_000 else email_parts.extract_inline_images(html_body)[0], mode, design, automated=automated, + ) + return _enqueue( + org_id, actor_uid, message_id=message_id, subject=subject, html_body=html_body, + mailbox_connection_id=mailbox_connection_id, from_email=connection.get("email"), brand_id=brand.get("brand_id"), + database_id=database_id, email_column=email_column, segment=segment or [], row_ids=[r["row_id"] for r in rows], + attachments=attachments, certificate=certificate if spec else None, attachment_names=[a.get("filename") for a in attachments or []], + scheduled_at=scheduled_at, window=window, + ) + + +def _enqueue(org_id: str, actor_uid: str, *, row_ids: list[str], html_body: str, attachments: list[dict] | None, certificate: dict | None, **fields) -> str: + send_id = uuid.uuid4().hex + created = _now() + db.set_doc(_payload_path(org_id, send_id), {"html_body": html_body, "attachments": attachments or [], "certificate": certificate}) + db.set_doc( + _send_path(org_id, send_id), + { + **fields, + "certificate": certificate is not None, + "created_by": actor_uid, + "created_at": created, + "sent_at": fields.get("scheduled_at") or created, + "status": "queued", + "note": "", + "pending": row_ids, + "total": len(row_ids), + "per_recipient": {}, + }, + ) + _set_active(org_id, send_id, True) + return send_id + + +def process_send(org_id: str, send_id: str, now: datetime | None = None, budget_seconds: float | None = None) -> dict: + """Sends what can go right now for one queued send, then returns its record. Safe to call + at any time and from several places: it does nothing unless the send is due, inside its + window, within the mailbox's daily limit and the organisation's hourly cap, and only one + caller works on a send at once. The rest stays queued for the next call.""" + lock = _locks.setdefault((org_id, send_id), threading.Lock()) + if not lock.acquire(blocking=False): + return get_send(org_id, send_id) + try: + # Other servers may be running too: the lease makes sure only one works this send. + # It outlasts the work it covers, so a crash frees it on its own a little later. + key, holder = f"send-{org_id}-{send_id}", f"{_WORKER}-{threading.get_ident()}" + if not db.claim_lease(key, holder, (budget_seconds or 900) + 120): + return get_send(org_id, send_id) + try: + return _process(org_id, send_id, now or datetime.now(timezone.utc), budget_seconds) + finally: + db.release_lease(key, holder) + finally: + lock.release() + + +def _process(org_id: str, send_id: str, now: datetime, budget_seconds: float | None) -> dict: + send = get_send(org_id, send_id) + if send.get("status") not in ACTIVE: + return send + if send.get("scheduled_at") and _parse_when(send["scheduled_at"]) > now: + return send + stamp = now.isoformat() + pending: list[str] = list(send.get("pending", [])) + if not pending: + return _finish(org_id, send_id, send) + if not _in_window(send.get("window"), now): + return _note(org_id, send_id, send, "Waiting for the sending window to open.") + + try: + connection = mailboxes.get_mailbox(org_id, send["mailbox_connection_id"]) + database = workbook.for_sending(org_id, send["database_id"], databases.get_database(org_id, send["database_id"])) + except orgs.NotFoundError: + return _stop(org_id, send_id, send, "paused", "The mailbox or the list for this send was removed. Resume after restoring it, or cancel.") + if connection["status"] != "verified": + return _stop(org_id, send_id, send, "paused", "The mailbox is not working. Fix it in Settings, then resume.") + + box = mailboxes.mailbox_settings(connection) + room = len(pending) + reason = "" + if box["daily_limit"]: + left = max(box["daily_limit"] - sent_today(org_id, send["mailbox_connection_id"], now), 0) + if left < room: + room, reason = left, f"The mailbox's daily limit of {box['daily_limit']} is reached. Sending continues tomorrow." + hourly = rate_limiter.remaining_capacity(org_id) + if hourly < room: + room, reason = hourly, "Waiting for the hourly sending limit. Sending continues as room opens up." + if room <= 0: + return _note(org_id, send_id, send, reason) + rate_limiter.check_and_consume(org_id, room) + + payload = db.get_doc(_payload_path(org_id, send_id)) or {} + shared_files = email_parts.decode_attachments(payload.get("attachments")) + spec = certificates.parse_spec(payload["certificate"]) if payload.get("certificate") else None + html_body, inline_images = email_parts.extract_inline_images(payload.get("html_body", "")) + rows = {r["row_id"]: r for r in databases.list_rows(org_id, send["database_id"])} + columns = database["columns"] + email_column = send.get("email_column") + try: + email_column = _email_column(database, email_column) + except ValueError: # renamed or retyped since the send was queued + email_column = _email_column(database) + blocked = unsubscribe.suppressed(org_id, send.get("from_email") or "") + + brand = brands.brand_for_mailbox(org_id, send["mailbox_connection_id"]) or {} + prefs = settings.email_settings(org_id) + credentials = mailboxes.get_decrypted_credentials(org_id, send["mailbox_connection_id"]) + try: + mailer = mailer_client.get_mailer(connection["kind"], credentials) + except (AuthError, ConnectionFailure, OSError) as exc: + # The mailbox's server can't be reached right now. Keep the queue and try again on the + # next run instead of failing the whole background run. + log.warning("Could not open the mailbox for send %s: %s", send_id, exc) + return _note(org_id, send_id, send, f"Could not reach the mailbox's server ({exc}). M8ion will try again shortly.") + if hasattr(mailer, "configure"): + mailer.configure( + box["from_name"] or brand.get("from_name") or prefs["from_name"], + box["reply_to"] or brand.get("reply_to") or prefs["reply_to"], + prefs["save_sent_copy"] if box["save_sent_copy"] is None else box["save_sent_copy"], + ) + + per_recipient = dict(send.get("per_recipient", {})) + started = time.monotonic() + sent_now = 0 + status = "sending" + save_every = 10 + + def save(final: bool = False) -> None: + # The status is only written at the end, so a pause pressed meanwhile is not overwritten. + update = {"pending": pending, "per_recipient": per_recipient, "note": reason} + if final: + update["status"] = status + db.update_doc(_send_path(org_id, send_id), update) + + while pending and sent_now < room: + row_id = pending[0] + row = rows.get(row_id) + address = row.get(email_column) if row and email_column else None + if row is None or not address: + per_recipient[row_id] = {"status": "skipped", "error": "No longer in the list", "at": stamp} + elif address.strip().lower() in blocked: + per_recipient[row_id] = {"status": "skipped", "error": "Unsubscribed", "at": stamp} + else: + if sent_now and prefs["pause_seconds"]: + time.sleep(prefs["pause_seconds"]) + files = list(shared_files) + try: + if spec is not None: + files.append(certificates.attachment_for(spec, row, columns)) + reference = mailer.send( + to_addr=address, + subject=substitute_placeholders(send["subject"], row, columns), + body=substitute_placeholders(html_body, row, columns, html=True) + unsubscribe.footer_html(org_id, address, send.get("from_email") or "", send_id), + attachments=files, inline_images=inline_images, headers=unsubscribe.headers(org_id, address, send.get("from_email") or "", send_id), + ) + # "sent" means the mailbox's own server accepted the message. Whether it then + # reached the inbox is only known from bounces (Phase 2); the Message-ID lets the + # hosting provider trace a message in their logs. + per_recipient[row_id] = {"status": "sent", "error": None, "at": stamp} + if isinstance(reference, str): + per_recipient[row_id]["reference"] = reference + except (AuthError, ConnectionFailure, OSError) as exc: + per_recipient[row_id] = {"status": "failed", "error": str(exc), "at": stamp} + sent_now += 1 + pending.pop(0) + if len(per_recipient) % save_every == 0: + save() + # A pause or cancel pressed while this runs takes effect within a few emails. + if (db.get_doc(_send_path(org_id, send_id)) or {}).get("status") not in ACTIVE: + break + if budget_seconds is not None and time.monotonic() - started > budget_seconds: + reason = "Sending continues on the next run." + break + if hasattr(mailer, "close"): + mailer.close() + + current = (db.get_doc(_send_path(org_id, send_id)) or {}).get("status") + if current not in ACTIVE: # paused or cancelled while sending: keep that, save the progress + status = current + elif not pending: + status = "done" + reason = "" + elif not reason and sent_now >= room: + reason = "Sending continues shortly." + save(final=True) + if sent_now: + delivery.watch(org_id, send_id) # look for delays, bounces and replies over the next days + if status not in ACTIVE: + _set_active(org_id, send_id, False) + return get_send(org_id, send_id) + + +def _note(org_id: str, send_id: str, send: dict, note: str) -> dict: + if send.get("note") != note: + db.update_doc(_send_path(org_id, send_id), {"note": note}) + return send | {"note": note} + + +def _stop(org_id: str, send_id: str, send: dict, status: str, note: str) -> dict: + db.update_doc(_send_path(org_id, send_id), {"status": status, "note": note}) + _set_active(org_id, send_id, False) + return send | {"status": status, "note": note} + + +def _finish(org_id: str, send_id: str, send: dict) -> dict: + db.update_doc(_send_path(org_id, send_id), {"status": "done", "note": ""}) + _set_active(org_id, send_id, False) + return send | {"status": "done", "note": ""} + + +def run_due(now: datetime | None = None, budget_seconds: float = 240) -> dict: + """Carries out every active send that is due. A timer calls this every minute or so (Cloud + Scheduler in production, a small thread when running locally); each run does a bounded + amount of work and exits.""" + started = time.monotonic() + checked = 0 + for doc in list(db.query_prefix("active_sends/").values()): + left = budget_seconds - (time.monotonic() - started) + if left <= 0: + break + try: + process_send(doc["org_id"], doc["send_id"], now, left) + except orgs.NotFoundError: + _set_active(doc["org_id"], doc["send_id"], False) + checked += 1 + return {"checked": checked} + + +def control_send(org_id: str, actor_uid: str, send_id: str, action: str) -> dict: + """Pause, resume or cancel a send that has not finished.""" + orgs.require_permission(org_id, actor_uid, "send") + send = get_send(org_id, send_id) + status = send.get("status", "done") + if action == "pause" and status in ACTIVE: + update = {"status": "paused", "note": "Paused."} + elif action == "resume" and status == "paused": + update = {"status": "queued", "note": ""} + elif action == "cancel" and status in ACTIVE + ("paused",): + update = {"status": "cancelled", "note": "Cancelled."} + else: + raise ValueError(f"This send is {status}, so it cannot be {action}d" if action != "cancel" else f"This send is {status}, so it cannot be cancelled") + db.update_doc(_send_path(org_id, send_id), update) + _set_active(org_id, send_id, update["status"] == "queued") + return get_send(org_id, send_id) + + +def sent_today(org_id: str, mailbox_connection_id: str, now: datetime | None = None) -> int: + """Emails this mailbox's server accepted since midnight UTC.""" + today = (now or datetime.now(timezone.utc)).astimezone(timezone.utc).date().isoformat() + total = 0 + for send in db.query_prefix(f"orgs/{org_id}/sends/").values(): + if send.get("mailbox_connection_id") != mailbox_connection_id: + continue + for r in send["per_recipient"].values(): + if r["status"] == "sent" and str(r.get("at") or send.get("sent_at", "")).startswith(today): + total += 1 + # Messages other products sent through the API count too. + for msg in db.query_prefix(f"orgs/{org_id}/api_messages/").values(): + if msg.get("mailbox_connection_id") == mailbox_connection_id: + total += sum(1 for r in msg.get("per_recipient", {}).values() if r.get("status") == "sent" and str(r.get("at", "")).startswith(today)) + return total + + +def get_send(org_id: str, send_id: str) -> dict: + doc = db.get_doc(_send_path(org_id, send_id)) + if doc is None: + raise orgs.NotFoundError(f"No send {send_id!r} in org {org_id!r}") + return doc + + +def list_sends(org_id: str, actor_uid: str, limit: int = 50) -> list[dict]: + """Recent sends, newest first, with counts instead of the per-recipient map.""" + orgs.require_permission(org_id, actor_uid) + prefix = f"orgs/{org_id}/sends/" + out = [] + for path, doc in db.query_prefix(prefix).items(): + statuses = [r.get("status") for r in (doc.get("per_recipient") or {}).values()] + subject = doc.get("subject") + if subject is None and doc.get("message_id"): + try: + subject = messages.get_message(org_id, doc["message_id"])["subject"] + except orgs.NotFoundError: + subject = "" + out.append({ + "send_id": path[len(prefix):], + "subject": subject or "", + "database_id": doc.get("database_id"), + "mailbox_connection_id": doc.get("mailbox_connection_id"), + "sent_at": doc.get("sent_at"), + "sent": statuses.count("sent"), + "failed": statuses.count("failed"), + "skipped": statuses.count("skipped"), + "pending": len(doc.get("pending") or []), + "status": doc.get("status", "done"), + "scheduled_at": doc.get("scheduled_at"), + "note": doc.get("note", ""), + "attachment_names": doc.get("attachment_names", []), + "certificate": bool(doc.get("certificate")), + "preset_id": doc.get("preset_id"), + "layout_key": doc.get("layout_key"), + }) + out.sort(key=lambda s: s["sent_at"] or "", reverse=True) + return out[:limit] + + +def get_send_details(org_id: str, actor_uid: str, send_id: str) -> dict: + """Everything about one send for its details page: who it went to (addresses looked up from + the list now, since the send record keeps row ids only), how each went, where it came from, + and the email itself so it can be read again or saved as a preset.""" + orgs.require_permission(org_id, actor_uid) + send = get_send(org_id, send_id) + try: + message = messages.get_message(org_id, send["message_id"]) + except (orgs.NotFoundError, KeyError): + message = {} + + database = None + try: + database = databases.get_database(org_id, send["database_id"]) + except orgs.NotFoundError: + pass + addresses: dict[str, str] = {} + column = send.get("email_column") + if database is not None: + try: + column = _email_column(database, column) + except ValueError: # the column was renamed or retyped since + column = _email_column(database) + if column: + addresses = {r["row_id"]: str(r.get(column) or "") for r in databases.list_rows(org_id, send["database_id"])} + + try: + mailbox_email = mailboxes.get_mailbox(org_id, send["mailbox_connection_id"]).get("email") + except (orgs.NotFoundError, KeyError): + mailbox_email = send.get("from_email") + + try: + tracking = bool(mailboxes.get_mailbox(org_id, send["mailbox_connection_id"]).get("has_imap")) + except (orgs.NotFoundError, KeyError): + tracking = False + recipients = [ + { + "row_id": row_id, + "address": addresses.get(row_id) or None, + "status": r.get("status"), + "error": r.get("error"), + "reference": r.get("reference"), + "delivery": delivery.shown_state(r, tracking=tracking), + } + for row_id, r in (send.get("per_recipient") or {}).items() + ] + waiting = "queued" if send.get("status") in ACTIVE + ("paused",) else "not sent" + recipients += [ + {"row_id": row_id, "address": addresses.get(row_id) or None, "status": waiting, "error": None, "reference": None, "delivery": delivery.shown_state({"status": waiting})} + for row_id in send.get("pending") or [] + ] + recipients.sort(key=lambda r: (r["status"] != "failed", (r["address"] or "~").lower())) + return { + "send_id": send_id, + "subject": send.get("subject") or message.get("subject") or "", + "sent_at": send.get("sent_at"), + "status": send.get("status", "done"), + "note": send.get("note", ""), + "scheduled_at": send.get("scheduled_at"), + "window": send.get("window"), + "from_email": mailbox_email, + "database_id": send.get("database_id"), + "database_name": database.get("name") if database else None, + "email_column": column, + "segment": send.get("segment") or [], + "attachment_names": send.get("attachment_names", []), + "certificate": bool(send.get("certificate")), + "recipients": recipients, + "html_body": message.get("html_body", ""), + "mode": message.get("mode") or "html", + "design": message.get("design"), + } diff --git a/backend/settings.py b/backend/settings.py new file mode 100644 index 0000000000000000000000000000000000000000..ea3f2f20e5b8cadd0e79eb7f19c1e2ab940cf33b --- /dev/null +++ b/backend/settings.py @@ -0,0 +1,197 @@ +""" +Settings, in two scopes: + +- Personal (per person, per org): the name shown in the console and which notices they want. + Any member edits their own. +- Organisation: the org's name (owner or admin) and how its emails go out (operator or above): + the sender name beside the address, a reply-to address, the mailbox the composer picks by + default, and whether a copy of each email is filed in the mailbox's Sent folder. + +Defaults live here, so a setting nobody has touched still reads as a full set of values. +""" + +from __future__ import annotations + +import re +from datetime import datetime, timezone + +from backend import firestore_client as db +from backend import mailboxes, orgs + +_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$") +_MAX_NAME = 80 + +NOTIFICATION_KEYS = ("campaign_finished", "emails_turned_away", "mailbox_problem", "new_signup", "weekly_summary") +DEFAULT_NOTIFICATIONS = { + "campaign_finished": False, + "emails_turned_away": True, + "mailbox_problem": True, + "new_signup": False, + "weekly_summary": False, +} +DEFAULT_EMAILS = {"from_name": "", "reply_to": "", "default_mailbox_id": "", "save_sent_copy": True, "pause_seconds": 2} +# Seconds M8ion waits between two emails of a campaign. Some mail servers accept a fast burst and +# then never deliver it, so campaigns are spaced out unless the organisation turns this down. +MAX_PAUSE_SECONDS = 30 +ORG_PROFILE_FIELDS = ("website", "domain", "country", "state", "lga", "address", "postal_code", "timezone") +_DOMAIN_RE = re.compile(r"^(?=.{3,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$") + + +def _now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def _personal_path(org_id: str, uid: str) -> str: + return f"orgs/{org_id}/personal_settings/{uid}" + + +def _emails_path(org_id: str) -> str: + return f"orgs/{org_id}/settings/emails" + + +def _clean_name(value: str, what: str) -> str: + value = " ".join(str(value or "").split()) + if len(value) > _MAX_NAME: + raise ValueError(f"Keep the {what} to {_MAX_NAME} characters or fewer") + return value + + +def get_settings(org_id: str, uid: str) -> dict: + """Everything the Settings pages show, with defaults filled in.""" + role = orgs.require_permission(org_id, uid) + permissions = sorted(orgs.permissions_for(org_id, role)) + personal = db.get_doc(_personal_path(org_id, uid)) or {} + return { + "role": role, + "permissions": permissions, + "profile": profile_of(org_id, uid, personal), + "organisation": organisation(org_id), + "notifications": DEFAULT_NOTIFICATIONS | {k: bool(v) for k, v in (personal.get("notifications") or {}).items() if k in NOTIFICATION_KEYS}, + "emails": email_settings(org_id), + } + + +def email_settings(org_id: str) -> dict: + """How the org's emails go out. Read by the send itself, so it takes no actor.""" + return DEFAULT_EMAILS | {k: v for k, v in (db.get_doc(_emails_path(org_id)) or {}).items() if k in DEFAULT_EMAILS} + + +PROFILE_EXTRAS = ("job_title", "phone", "about") + + +def profile_of(org_id: str, uid: str, personal: dict | None = None) -> dict: + """The person's own profile: what they chose to share, plus facts about their use of this organisation.""" + personal = personal if personal is not None else (db.get_doc(_personal_path(org_id, uid)) or {}) + member = db.get_doc(f"orgs/{org_id}/members/{uid}") or {} + sends = [d for d in db.query_prefix(f"orgs/{org_id}/sends/").values() if d.get("created_by") == uid] + return { + "display_name": personal.get("display_name", ""), + **{k: personal.get(k, "") for k in PROFILE_EXTRAS}, + "active_since": member.get("added_at"), + "campaigns_sent": len(sends), + "last_active": max((d.get("created_at") or "" for d in sends), default="") or None, + } + + +def update_profile(org_id: str, uid: str, display_name: str, extras: dict | None = None) -> dict: + orgs.require_permission(org_id, uid) + name = _clean_name(display_name, "name") + update = {"display_name": name} + for key in PROFILE_EXTRAS: + if extras and key in extras: + limit = 500 if key == "about" else 80 + value = " ".join(str(extras[key] or "").split()) if key != "about" else str(extras[key] or "").strip() + if len(value) > limit: + raise ValueError(f"Keep this to {limit} characters or fewer") + update[key] = value + _merge(_personal_path(org_id, uid), update) + return profile_of(org_id, uid) + + +def update_notifications(org_id: str, uid: str, values: dict) -> dict: + orgs.require_permission(org_id, uid) + unknown = set(values) - set(NOTIFICATION_KEYS) + if unknown: + raise ValueError(f"Unknown notice: {', '.join(sorted(unknown))}") + current = get_settings(org_id, uid)["notifications"] | {k: bool(v) for k, v in values.items()} + _merge(_personal_path(org_id, uid), {"notifications": current}) + return current + + +def organisation(org_id: str) -> dict: + org = orgs.get_org(org_id) + profile = org.get("profile") or {} + return {"name": org["name"], **{k: profile.get(k, "") for k in ORG_PROFILE_FIELDS}} + + +def rename_org(org_id: str, uid: str, name: str, profile: dict | None = None) -> dict: + """Saves the org's name and its details: website, main domain, country, state, LGA, postal + address and postal code (many countries' email laws ask for one in marketing emails) and time zone.""" + orgs.require_permission(org_id, uid, "manage_settings") + name = _clean_name(name, "organisation name") + if not name: + raise ValueError("Give the organisation a name") + update: dict = {"name": name} + if profile is not None: + unknown = set(profile) - set(ORG_PROFILE_FIELDS) + if unknown: + raise ValueError(f"Unknown organisation detail: {', '.join(sorted(unknown))}") + clean = {k: " ".join(str(profile.get(k) or "").split()) for k in ORG_PROFILE_FIELDS} + if len(clean["address"]) > 300: + raise ValueError("Keep the address to 300 characters or fewer") + if len(clean["postal_code"]) > 20: + raise ValueError("Keep the postal code to 20 characters or fewer") + for key in ("country", "state", "lga"): + if len(clean[key]) > 100: + raise ValueError(f"Keep the {key} to 100 characters or fewer") + clean["domain"] = clean["domain"].lower().removeprefix("https://").removeprefix("http://").removeprefix("www.").rstrip("/") + if clean["domain"] and not _DOMAIN_RE.match(clean["domain"]): + raise ValueError("Enter a domain like yourcompany.com") + if clean["website"] and not clean["website"].startswith(("https://", "http://")): + clean["website"] = "https://" + clean["website"] + if clean["timezone"]: + try: + from zoneinfo import ZoneInfo + ZoneInfo(clean["timezone"]) + except Exception as exc: # noqa: BLE001 + raise ValueError("Pick a time zone from the list") from exc + update["profile"] = clean + db.update_doc(f"orgs/{org_id}", update) + return organisation(org_id) + + +def update_emails(org_id: str, uid: str, values: dict) -> dict: + orgs.require_permission(org_id, uid, "manage_settings") + unknown = set(values) - set(DEFAULT_EMAILS) + if unknown: + raise ValueError(f"Unknown email setting: {', '.join(sorted(unknown))}") + clean: dict = {} + if "from_name" in values: + clean["from_name"] = _clean_name(values["from_name"], "sender name").replace('"', "") + if "reply_to" in values: + reply_to = str(values["reply_to"] or "").strip() + if reply_to and not _EMAIL_RE.match(reply_to): + raise ValueError("The reply-to address does not look like an email address") + clean["reply_to"] = reply_to + if "default_mailbox_id" in values: + mailbox_id = str(values["default_mailbox_id"] or "") + if mailbox_id: + mailboxes.get_mailbox(org_id, mailbox_id) # raises NotFoundError for another org's id + clean["default_mailbox_id"] = mailbox_id + if "save_sent_copy" in values: + clean["save_sent_copy"] = bool(values["save_sent_copy"]) + if "pause_seconds" in values: + try: + pause = float(values["pause_seconds"] or 0) + except (TypeError, ValueError) as exc: + raise ValueError("The pause must be a number of seconds") from exc + if not 0 <= pause <= MAX_PAUSE_SECONDS: + raise ValueError(f"The pause must be between 0 and {MAX_PAUSE_SECONDS} seconds") + clean["pause_seconds"] = pause + _merge(_emails_path(org_id), clean) + return email_settings(org_id) + + +def _merge(path: str, values: dict) -> None: + doc = db.get_doc(path) or {} + db.set_doc(path, doc | values | {"updated_at": _now()}) diff --git a/backend/smtp_check.py b/backend/smtp_check.py new file mode 100644 index 0000000000000000000000000000000000000000..582a12027f6da8631fd0765c26be98d9166fee9e --- /dev/null +++ b/backend/smtp_check.py @@ -0,0 +1,32 @@ +"""Checks whether this server can reach a mail server. Connects and says hello only: no sign-in, +no email. Run: python -m backend.smtp_check mail.example.com 465 [993 ...]""" + +from __future__ import annotations + +import smtplib +import socket +import ssl +import sys + + +def check(host: str, port: int) -> str: + try: + if port == 465: + with smtplib.SMTP_SSL(host, port, timeout=15, context=ssl.create_default_context()) as s: + return f"{host}:{port} reached (SMTP, TLS) - {s.ehlo()[0]}" + if port == 587: + with smtplib.SMTP(host, port, timeout=15) as s: + s.starttls(context=ssl.create_default_context()) + return f"{host}:{port} reached (SMTP, STARTTLS) - {s.ehlo()[0]}" + with socket.create_connection((host, port), timeout=15) as raw: + with ssl.create_default_context().wrap_socket(raw, server_hostname=host): + return f"{host}:{port} reached (TLS)" + except Exception as exc: # report every kind of failure the same way + return f"{host}:{port} NOT reached - {type(exc).__name__}: {exc}" + + +if __name__ == "__main__": + host, *ports = sys.argv[1:] + results = [check(host, int(p)) for p in ports or ["465"]] + print("\n".join(results)) + sys.exit(0 if all("NOT reached" not in r for r in results) else 1) diff --git a/backend/smtp_mailer.py b/backend/smtp_mailer.py new file mode 100644 index 0000000000000000000000000000000000000000..b64548c0f0afc5118b282988af66eacc60c89c6e --- /dev/null +++ b/backend/smtp_mailer.py @@ -0,0 +1,291 @@ +""" +The real counterpart to backend/mock_mailer.py โ same interface (`.send(to_addr, subject, +body)`, same AuthError/ConnectionFailure exceptions on connect), but an actual SMTP+STARTTLS +connection instead of an in-memory simulation. Only handles kind="smtp" connections (raw +host/port/username/password) โ real OAuth sending needs a real Google Cloud OAuth app, +which doesn't exist yet (see docs/engineering/env-config-reference.md). + +Reusing mock_mailer's exception classes (not defining new ones) is deliberate: every caller +that already catches AuthError/ConnectionFailure around a mailer call works unchanged +whether the mailer underneath is real or mocked. +""" + +from __future__ import annotations + +import html +import imaplib +import logging +import re +import smtplib +import ssl +import time +from email import encoders +from email.mime.base import MIMEBase +from email.mime.image import MIMEImage +from email.mime.multipart import MIMEMultipart +from email.mime.text import MIMEText +from email.utils import formataddr, formatdate, make_msgid + +from backend.delivery import imap_details +from backend.email_parts import Attachment, InlineImage +from backend.mock_mailer import AuthError, ConnectionFailure + + +# Port 465 is implicit TLS (the connection is SSL-wrapped from the first byte) โ it must use +# SMTP_SSL, never SMTP()+starttls(), which assumes a plaintext handshake first. Mixing the two +# up doesn't raise a clean auth/protocol error, it just hangs until the socket times out, so an +# implicit-TLS host on 465 was silently indistinguishable from a genuinely unreachable one. +IMPLICIT_TLS_PORT = 465 + +log = logging.getLogger(__name__) + + +def clean_password(password: str) -> str: + """App passwords are shown in groups ("abcd efgh ijkl mnop") and get pasted with the + spaces, but the spaces are never part of the password, so they are ignored here.""" + return "".join(password.split()) + + +class SMTPMailer: + def __init__(self, credentials: dict): + host = credentials["host"] + port = credentials["port"] + username = credentials["username"].strip() + password = clean_password(credentials["password"]) + + # Phase 1: reach the server and secure the connection. A failure here really is + # "couldn't reach the server". + try: + if port == IMPLICIT_TLS_PORT: + self._server = smtplib.SMTP_SSL(host, port, timeout=15, context=ssl.create_default_context()) + else: + self._server = smtplib.SMTP(host, port, timeout=15) + self._server.starttls(context=ssl.create_default_context()) + self._server.ehlo() + except (smtplib.SMTPException, OSError) as exc: + log.warning("SMTP connection to %s:%s failed: %r", host, port, exc) + raise ConnectionFailure(str(exc)) from exc + + # Phase 2: sign in. smtplib's login() retries every mechanism the server offers, and + # Gmail hangs up after the second rejected attempt, so a wrong password surfaced as + # SMTPServerDisconnected ("couldn't reach the server"). One mechanism gives the + # provider's real answer, and a hang-up during sign-in is treated as a rejection. + try: + if self._server.has_extn("auth") and "PLAIN" in self._server.esmtp_features["auth"].upper().split(): + self._server.user, self._server.password = username, password + self._server.auth("PLAIN", self._server.auth_plain, initial_response_ok=True) + else: + self._server.login(username, password) + except (smtplib.SMTPAuthenticationError, smtplib.SMTPServerDisconnected) as exc: + log.warning("SMTP sign-in rejected by %s:%s for %s: %s", host, port, username, exc) + raise AuthError(str(exc)) from exc + except (smtplib.SMTPException, OSError) as exc: + log.warning("SMTP sign-in to %s:%s failed: %r", host, port, exc) + raise ConnectionFailure(str(exc)) from exc + + self._from_addr = username + self._from_name = "" + self._reply_to = "" + self._sent_copy: SentCopy | None = SentCopy(host, username, password, imap=imap_details(credentials)) + + def configure(self, from_name: str = "", reply_to: str = "", save_sent_copy: bool = True) -> None: + """The org's email settings (backend/settings.py): the name shown beside the address, + where replies go, and whether a copy is filed in Sent.""" + self._from_name, self._reply_to = from_name.strip(), reply_to.strip() + if not save_sent_copy and self._sent_copy is not None: + self._sent_copy.close() + self._sent_copy = None + + def send(self, to_addr: str, subject: str, body: str, + attachments: list[Attachment] | None = None, inline_images: list[InlineImage] | None = None, + headers: dict[str, str] | None = None) -> str: + """Hands one message to the server and returns its Message-ID. Raises + ConnectionFailure when the server refuses it, including refusing the recipient.""" + msg = build_message(body, attachments or [], inline_images or []) + msg["Subject"] = subject + from_name = getattr(self, "_from_name", "") + msg["From"] = formataddr((from_name, self._from_addr)) if from_name else self._from_addr + msg["To"] = to_addr + if getattr(self, "_reply_to", ""): + msg["Reply-To"] = self._reply_to + # Date and Message-ID are required by RFC 5322. Some servers add them on the way out, + # many hosting servers don't, and Gmail turns away mail that arrives without a + # Message-ID, so every message carries its own. + for name, value in (headers or {}).items(): + msg[name] = value + msg["Date"] = formatdate(usegmt=True) + msg["Message-ID"] = make_msgid(domain=self._from_addr.rpartition("@")[2] or None) + try: + refused = self._server.sendmail(self._from_addr, [to_addr], msg.as_string()) + except smtplib.SMTPException as exc: + raise ConnectionFailure(str(exc)) from exc + if refused: + code, reason = next(iter(refused.values())) + raise ConnectionFailure(f"{code} {reason.decode(errors='replace') if isinstance(reason, bytes) else reason}") + sent_copy = getattr(self, "_sent_copy", None) + if sent_copy is not None: + sent_copy.save(msg.as_bytes()) + return msg["Message-ID"] + + def close(self) -> None: + try: + self._server.quit() + except smtplib.SMTPException: + pass + sent_copy = getattr(self, "_sent_copy", None) + if sent_copy is not None: + sent_copy.close() + + +# Providers whose SMTP servers already file a copy of every message in Sent. Adding our own +# copy there would show each email twice. +_FILES_SENT_ITSELF = ("smtp.gmail.com", "smtp.googlemail.com", "smtp.office365.com", "smtp-mail.outlook.com") +_SENT_NAMES = ("Sent", "INBOX.Sent", "Sent Items", "Sent Messages", "INBOX.Sent Items", "Sent Mail") +_LIST_LINE = re.compile(r'\((?P]*)?>\s*(\{(?:if\s[^{}]*|else|/if)\})\s*
", re.IGNORECASE) +_PARAGRAPH_LIST = re.compile(r"]*)?>\s*\{([A-Za-z0-9_][A-Za-z0-9_ ]*?)(?:\|(bullets|inline))?\}\s*
", re.IGNORECASE) +_CONDITION = re.compile( + r"""^(?P; drop that wrapper so the + # block leaves no empty paragraphs behind. + return _PARAGRAPH_TOKEN.sub(r"\1", template) + + +def validate_template(template: str, columns: list[dict] | None = None) -> list[str]: + """Problems that would make the template render wrongly. Empty list means safe to send.""" + problems: list[str] = [] + try: + tree = _parse(_prepare(template)) + except TemplateError as exc: + return [str(exc)] + names = {c["name"] for c in (columns or [])} + if names: + def walk(nodes: list) -> None: + for n in nodes: + if isinstance(n, _If): + if n.cond.field not in names: + problems.append(f'A condition uses the field "{n.cond.field}", which this audience does not have') + walk(n.then) + walk(n.other) + walk(tree) + return list(dict.fromkeys(problems)) + + +def render(template: str, row: dict, columns: list[dict] | None = None, html: bool = True) -> str: + """Renders one recipient's copy. Raises TemplateError if the template is malformed.""" + tree = _parse(_prepare(template) if html else template) + return _render(tree, row, _column_defs(columns), html) diff --git a/backend/timing.py b/backend/timing.py new file mode 100644 index 0000000000000000000000000000000000000000..781b71c01f81edd2fa017f3e8234f736ceb59cdf --- /dev/null +++ b/backend/timing.py @@ -0,0 +1,18 @@ +""" +Everything that happens "when its time comes", run from one place so a single timer drives it: +queued and scheduled sends, and automations (sequences, recurring and date-based sends). +See docs/blueprint/adr/0004. +""" + +from __future__ import annotations + +from datetime import datetime + +from backend import automations, delivery, sending + + +def run_due(now: datetime | None = None, budget_seconds: float = 240) -> dict: + # Automations first, so the campaigns they make are picked up in the same pass. + made = automations.run_due(now) + sends = sending.run_due(now, budget_seconds) + return {"automations": made, "sends": sends, "delivery": delivery.run_due(now)} diff --git a/backend/unsubscribe.py b/backend/unsubscribe.py new file mode 100644 index 0000000000000000000000000000000000000000..f6146ba4cd7ba998ab0504da54b9076de5797e23 --- /dev/null +++ b/backend/unsubscribe.py @@ -0,0 +1,200 @@ +""" +Opting out of email. Every campaign email carries a signed link (and the one-click header mail +apps look for). The link holds the organisation, the address, the mailbox that sent it and the +campaign, signed so it cannot be forged or edited, and needs no sign-in. + +Opting out is per sending mailbox: someone can stop the newsletter and still get receipts from +another address. The page also offers stopping everything from the organisation. A record with +an empty mailbox applies to every mailbox (older records and "everything" choices). + + orgs/{org_id}/suppressions/{key} -- {email, mailbox, reason, how, send_id, subject, by, at} +""" + +from __future__ import annotations + +import base64 +import hashlib +import hmac +import html +import os +import re +from datetime import datetime, timezone + +from backend import crypto_utils, orgs +from backend import firestore_client as db + +_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$") + + +def _secret() -> bytes: + key = os.getenv("UNSUBSCRIBE_SECRET") or crypto_utils._key + return key.encode() if isinstance(key, str) else key + + +def public_base() -> str | None: + """This server's public https address. None until it has one: a local address in an email + can't be opened by the person reading it, and one-click unsubscribe needs https.""" + base = os.getenv("PUBLIC_BASE_URL", "").strip().rstrip("/") + return base if base.startswith("https://") else None + + +def _now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def _key(email: str, mailbox: str = "") -> str: + """Every-mailbox records keep the old key (the address alone) so existing ones still match.""" + text = email.strip().lower() + (f"|{mailbox.strip().lower()}" if mailbox.strip() else "") + return hashlib.sha256(text.encode()).hexdigest()[:32] + + +def _path(org_id: str, email: str, mailbox: str = "") -> str: + return f"orgs/{org_id}/suppressions/{_key(email, mailbox)}" + + +def _sign(payload: str) -> str: + return hmac.new(_secret(), payload.encode(), hashlib.sha256).hexdigest()[:32] + + +def make_token(org_id: str, email: str, mailbox: str = "", send_id: str = "") -> str: + body = f"2|{org_id}|{mailbox.strip().lower()}|{send_id}|{email.strip().lower()}" + payload = base64.urlsafe_b64encode(body.encode()).decode().rstrip("=") + return f"{payload}.{_sign(payload)}" + + +def read_token(token: str) -> dict: + """{org_id, email, mailbox, send_id} for a genuine token; ValueError for anything else. + Links sent before opting out was per mailbox hold no mailbox, which means every mailbox.""" + payload, _, signature = token.partition(".") + if not payload or not hmac.compare_digest(signature, _sign(payload)): + raise ValueError("This unsubscribe link is not valid") + try: + text = base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)).decode() + except Exception as exc: # undecodable payload + raise ValueError("This unsubscribe link is not valid") from exc + if text.startswith("2|"): + parts = text.split("|", 4) + if len(parts) != 5: + raise ValueError("This unsubscribe link is not valid") + _, org_id, mailbox, send_id, email = parts + else: + org_id, _, email = text.partition("|") + mailbox = send_id = "" + if not org_id or not _EMAIL_RE.match(email): + raise ValueError("This unsubscribe link is not valid") + return {"org_id": org_id, "email": email, "mailbox": mailbox, "send_id": send_id} + + +def parse_token(token: str) -> tuple[str, str]: + """(org_id, email) for a genuine token; ValueError for anything else.""" + t = read_token(token) + return t["org_id"], t["email"] + + +def link(org_id: str, email: str, sender: str = "", send_id: str = "") -> str: + """The signed page when there is a public address, otherwise an email back to the sending + mailbox asking to be removed, which someone adds to the list by hand. Empty if neither exists.""" + base = public_base() + if base: + return f"{base}/u/{make_token(org_id, email, sender, send_id)}" + return f"mailto:{sender}?subject=Unsubscribe" if sender else "" + + +def headers(org_id: str, email: str, sender: str = "", send_id: str = "") -> dict[str, str]: + """What mail apps read to show their own Unsubscribe button. One-click (RFC 8058) is https only.""" + url = link(org_id, email, sender, send_id) + if not url: + return {} + found = {"List-Unsubscribe": f"<{url}>"} + if url.startswith("https://"): + found["List-Unsubscribe-Post"] = "List-Unsubscribe=One-Click" + return found + + +def footer_html(org_id: str, email: str, sender: str = "", send_id: str = "") -> str: + """The line at the foot of every campaign email: who sent it, where, and how to opt out.""" + try: + org = orgs.get_org(org_id) + except orgs.NotFoundError: + org = {} + place = ", ".join(p for p in (org.get("address"), org.get("lga"), org.get("state"), org.get("postal_code"), org.get("country")) if p) + who = html.escape(" ยท ".join(p for p in (org.get("name"), place) if p)) + url = link(org_id, email, sender, send_id) + return ( + '
{html.escape(str(exc))}.
"), status_code=400) + every = ( + f'' if t["mailbox"] else "" + ) + return unsubscribe.page( + "Unsubscribe", + f"Stop emails from {_who(t)} to {html.escape(t['email'])}?
" + f'', + ) + + +@router.post("/u/{token}", response_class=HTMLResponse) +async def unsubscribe_now(token: str, request: Request): + """The page's buttons send a scope. Mail apps' one-click button sends + "List-Unsubscribe=One-Click" and opts out of the sending mailbox only.""" + try: + form = await request.form() + scope = form.get("scope") + t = unsubscribe.unsubscribe_with_token(token, everything=scope == "all", how="link" if scope else "one-click") + except ValueError as exc: + return HTMLResponse(unsubscribe.page("Link not valid", f"{html.escape(str(exc))}.
"), status_code=400) + who = _who(t) if t["mailbox"] else "this organisation" + return unsubscribe.page("You are unsubscribed", f"{html.escape(t['email'])} will not get more emails from {who}.
") diff --git a/backend/verification.py b/backend/verification.py new file mode 100644 index 0000000000000000000000000000000000000000..234b43996d4bfd09c427d9cc65fcd27383ed7107 --- /dev/null +++ b/backend/verification.py @@ -0,0 +1,79 @@ +""" +Staff side of identity checks. Each detail a person submits is reviewed on its own and is either +verified, or rejected with a reason the person can read. The overall status follows from the details: + + approved every required detail is verified + needs_changes at least one detail is rejected (the person fixes it and sends it again) + submitted otherwise: still waiting on a reviewer + +Reviews live in the same document as the submission, identity/{uid}.review[field]. When a person +sends their details again, a detail whose value did not change keeps its review; a changed one starts over. +""" + +from __future__ import annotations + +from datetime import datetime, timezone + +from backend import accounts, identity +from backend import firestore_client as db +from backend.auth import lookup_user +from backend import staff + +DECISIONS = ("verified", "rejected") + + +class VerificationError(Exception): + """The review can't be recorded as asked.""" + + +def _row(uid: str, doc: dict) -> dict | None: + account_type = accounts.account_type_of(uid) + if not account_type or not doc.get("values"): + return None + review = doc.get("review", {}) + values = doc.get("values", {}) + return { + "uid": uid, + "email": lookup_user(uid).get("email", "") or uid, + "account_type": account_type, + "status": doc.get("status", "submitted"), + "submitted_at": doc.get("submitted_at"), + "fields": [ + {"key": k, "label": label, "required": req, "value": values.get(k, ""), "review": review.get(k)} + for k, label, req in identity.FIELDS[account_type] + ], + } + + +def queue() -> list[dict]: + rows = [] + for path, doc in db.query_prefix("identity/").items(): + row = _row(path.split("/", 1)[1], doc) + if row: + rows.append(row) + # Waiting first, then those sent back, then those done; oldest first inside each. + order = {"submitted": 0, "needs_changes": 1, "approved": 2} + return sorted(rows, key=lambda r: (order.get(r["status"], 3), r["submitted_at"] or "")) + + +def review(actor_email: str, uid: str, field: str, decision: str, reason: str = "") -> dict: + staff.require(actor_email, "verification") + if decision not in DECISIONS: + raise VerificationError("Choose verified or rejected") + doc = db.get_doc(f"identity/{uid}") + account_type = accounts.account_type_of(uid) + if not doc or not account_type or not doc.get("values"): + raise VerificationError("Nothing to review for this account") + if field not in {k for k, _l, _r in identity.FIELDS[account_type]} or field not in doc["values"]: + raise VerificationError("That detail was not submitted") + reason = reason.strip()[:500] + if decision == "rejected" and len(reason) < 3: + raise VerificationError("Say why it is rejected so the person can fix it") + entry = {"decision": decision, "by": actor_email.strip().lower(), "at": datetime.now(timezone.utc).isoformat()} + if decision == "rejected": + entry["reason"] = reason + doc.setdefault("review", {})[field] = entry + doc["status"] = identity.overall_status(account_type, doc["review"]) + db.set_doc(f"identity/{uid}", doc) + staff.log(actor_email, f"identity.{decision}", uid, f"{field}" + (f": {reason}" if reason else "")) + return _row(uid, doc) diff --git a/backend/workbook.py b/backend/workbook.py new file mode 100644 index 0000000000000000000000000000000000000000..1a0c6d5db54289c76a81ca03f1b15af6913797ca --- /dev/null +++ b/backend/workbook.py @@ -0,0 +1,934 @@ +""" +The audience workbook: one main sheet ("Everyone") that holds every person once, keyed by +email address, with a Tags column, plus audiences, which are saved filters on that sheet. + +An audience is a strip of the main sheet, never a copy: editing a person changes them in every +audience they fall in. Uploading a file adds new people or fills in existing ones and tags them +with the upload's name, which also creates an audience for that tag. + +When a file gives a different answer for a field someone already has (another spelling of their +name, a second phone number), the newest answer goes in the sheet so sends use it, and every +answer is kept in a conflict record that the audiences page flags until someone picks one: + + orgs/{org_id}/conflicts/{key} -- {row_id, email, field, values: [{value, source, at}], resolved} + +Older orgs have separate sheets. combine_sheets folds them into the main sheet once, when the +owner asks, tagging each person with the sheet they came from. The old sheets are kept and +marked archived, so past campaigns still show which list they went to. +""" + +from __future__ import annotations + +import json +import uuid +import hashlib +from datetime import datetime, timezone + +from backend import databases, orgs +from backend import firestore_client as db +from backend.crypto_utils import decrypt, encrypt +from backend.templating import split_items + +MAIN_NAME = "Everyone" +TAGS = "Tags" +EMAIL = "Email" + + +def _now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def _audience_path(org_id: str, audience_id: str) -> str: + return f"orgs/{org_id}/audiences/{audience_id}" + + +# --- Different answers for the same person ---------------------------------------- + +def _conflict_path(org_id: str, row_id: str, field: str) -> str: + key = hashlib.sha256(f"{row_id}|{field}".encode()).hexdigest()[:32] + return f"orgs/{org_id}/conflicts/{key}" + + +def _same(a, b) -> bool: + return " ".join(str(a or "").split()).lower() == " ".join(str(b or "").split()).lower() + + +def _record_conflict(org_id: str, row_id: str, email: str, field: str, old: dict, new: dict) -> None: + """Keeps every answer given for one person's field. A record that was resolved opens again + when yet another answer arrives.""" + path = _conflict_path(org_id, row_id, field) + doc = db.get_doc(path) or {"row_id": row_id, "email": email, "field": field, "values": [], "created_at": _now()} + values = list(doc.get("values") or []) + added = False + for v in (old, new): + if not any(_same(x["value"], v["value"]) for x in values): + values.append(v) + added = True + if not added and "resolved" in doc: + return # nothing new; a choice someone already made stands + db.set_doc(path, doc | {"values": values, "resolved": False, "resolved_by": "", "resolved_at": ""}) + + +def _conflict_docs(org_id: str) -> dict[str, dict]: + prefix = f"orgs/{org_id}/conflicts/" + return {path[len(prefix):]: data for path, data in db.query_prefix(prefix).items()} + + +def _recount_conflicts(org_id: str, mid: str) -> int: + count = sum(1 for d in _conflict_docs(org_id).values() if not d.get("resolved")) + db.update_doc(databases._database_path(org_id, mid), {"open_conflicts": count}) + return count + + +def list_conflicts(org_id: str, actor_uid: str) -> list[dict]: + """Open conflicts, newest answer last in each, with the value the sheet holds now.""" + orgs.require_permission(org_id, actor_uid) + mid = main_id(org_id) + if not mid: + return [] + hub = refresh(org_id) + if is_split(hub): + rows = {str(r.get(EMAIL, "")).strip().lower(): r for r in databases.list_rows(org_id, mid)} + out = [] + for cid, d in _conflict_docs(org_id).items(): + if d.get("resolved") or "key" not in d: + continue + row = rows.get(d["email"]) or {} + out.append({"conflict_id": cid, "row_id": row.get("row_id", ""), "email": row.get(EMAIL) or d["email"], "field": d["field"], + "current": row.get(d["field"], ""), "values": d.get("values") or [], "created_at": d.get("created_at")}) + return sorted(out, key=lambda c: (c["email"].lower(), c["field"])) + rows = {r["row_id"]: r for r in databases.list_rows(org_id, mid)} + out = [] + for cid, d in _conflict_docs(org_id).items(): + if d.get("resolved"): + continue + row = rows.get(d["row_id"]) + if row is None: + continue + out.append({ + "conflict_id": cid, "row_id": d["row_id"], "email": d.get("email", ""), "field": d["field"], + "current": row.get(d["field"], ""), "values": d.get("values") or [], "created_at": d.get("created_at"), + }) + return sorted(out, key=lambda c: (c["email"], c["field"])) + + +def resolve_conflict(org_id: str, actor_uid: str, conflict_id: str, value: str) -> None: + """Puts the chosen answer in the sheet and closes the flag. The other answers stay on record.""" + orgs.require_permission(org_id, actor_uid, "edit_lists") + path = f"orgs/{org_id}/conflicts/{conflict_id}" + doc = db.get_doc(path) + if doc is None: + raise orgs.NotFoundError("That flag no longer exists.") + if not any(_same(v["value"], value) for v in doc.get("values") or []): + raise databases.ValidationError("Pick one of the answers given.") + mid = main_id(org_id) + if "key" in doc: + # The sheets keep what people typed; the choice is what Everyone and its sends use. + db.update_doc(path, {"resolved": True, "resolved_by": actor_uid, "resolved_at": _now(), "chosen": value}) + refresh(org_id, force=True) + return + databases.update_row(org_id, actor_uid, mid, doc["row_id"], {doc["field"]: value}) + db.update_doc(path, {"resolved": True, "resolved_by": actor_uid, "resolved_at": _now(), "chosen": value}) + _recount_conflicts(org_id, mid) + + +def check_old_sheets(org_id: str, actor_uid: str) -> dict: + """Looks through the sheets that were combined for answers that differ from the main sheet + and flags them. Changes no values: combining kept the first answer, and the flag lets + someone choose.""" + orgs.require_permission(org_id, actor_uid, "edit_lists") + mid = main_id(org_id) + if not mid: + return {"flagged": 0} + main = databases.get_database(org_id, mid) + if is_split(main): + return {"flagged": 0, "open": main.get("open_conflicts", 0)} + main_email = _email_column(main["columns"]) or EMAIL + people = {str(r.get(main_email, "")).strip().lower(): r for r in databases.list_rows(org_id, mid) if str(r.get(main_email, "")).strip()} + before = sum(1 for d in _conflict_docs(org_id).values() if not d.get("resolved")) + for did, sheet in databases.list_databases(org_id).items(): + if not sheet.get("archived"): + continue + src_email = _email_column(sheet.get("columns") or []) + if not src_email: + continue + at = sheet.get("created_at", "") + for row in _full_rows(org_id, did, sheet): + email = str(row.get(src_email, "") or "").strip().lower() + person = people.get(email) + if person is None: + continue + for k, v in row.items(): + field = main_email if k == src_email else k + if field in (TAGS, "row_id", main_email) or v in (None, ""): + continue + current = person.get(field) + if current not in (None, "") and not _same(current, v): + _record_conflict(org_id, person["row_id"], email, field, + {"value": current, "source": "Everyone", "at": ""}, + {"value": v, "source": sheet.get("name", ""), "at": at}) + after = _recount_conflicts(org_id, mid) + return {"flagged": max(0, after - before), "open": after} + + +# --- The main sheet ---------------------------------------------------------------- + +def main_id(org_id: str) -> str | None: + for did, data in databases.list_databases(org_id).items(): + if data.get("is_main"): + return did + return None + + +def _email_column(columns: list[dict]) -> str | None: + return next((c["name"] for c in columns if c["type"] == "email"), None) + + +def _create_main(org_id: str) -> str: + database_id = uuid.uuid4().hex + db.set_doc(databases._database_path(org_id, database_id), { + "name": MAIN_NAME, + "is_main": True, + "source_filename": "", + "source_kind": "workbook", + "created_at": _now(), + "row_count": 0, + "columns": [ + {"name": EMAIL, "type": "email", "flagged_row_ids": []}, + {"name": TAGS, "type": "tag", "delimiter": ";", "flagged_row_ids": []}, + ], + "lookup_tables": [], + "suggestions": [], + }) + return database_id + + +def _add_tag(text: str, tag: str) -> str: + tags = split_items(text or "", ";") + if tag and tag.lower() not in {t.lower() for t in tags}: + tags.append(tag) + return "; ".join(tags) + + +def _full_rows(org_id: str, database_id: str, sheet: dict) -> list[dict]: + """A sheet's rows with any columns that older uploads moved out into lookup tables joined + back in, so nothing is lost when the sheet is folded into the main one.""" + rows = databases.list_rows(org_id, database_id) + for lookup in sheet.get("lookup_tables") or []: + try: + table = databases.get_lookup_table(org_id, database_id, lookup["name"]) + except orgs.NotFoundError: + continue + key, *rest = table["columns"] + by_key = {str(r.get(key)): r for r in table["rows"]} + for row in rows: + match = by_key.get(str(row.get(key))) + if match: + for c in rest: + row.setdefault(c, match.get(c)) + return rows + + +def _upsert(org_id: str, incoming: list[dict], incoming_columns: list[dict], tag: str) -> dict: + """Adds `incoming` rows to the main sheet. A row whose email is already there fills in that + person's blank cells and gains the tag; anything else becomes a new person. A different + answer for a filled cell replaces it, so sends use the newest, and both answers are kept in + a conflict record for someone to review. Returns counts.""" + mid = main_id(org_id) or _create_main(org_id) + main = databases.get_database(org_id, mid) + columns = list(main["columns"]) + main_email = _email_column(columns) or EMAIL + known = {c["name"] for c in columns} + if TAGS not in known: + columns.append({"name": TAGS, "type": "tag", "delimiter": ";", "flagged_row_ids": []}) + known.add(TAGS) + + # The incoming sheet's email column lands in the main email column whatever it was called. + src_email = _email_column(incoming_columns) + rename = {src_email: main_email} if src_email else {} + for col in incoming_columns: + name = rename.get(col["name"], col["name"]) + if name in known or name == "row_id": + continue + new_col = {k: v for k, v in col.items() if k != "flagged_row_ids"} | {"name": name, "flagged_row_ids": []} + columns.append(new_col) + known.add(name) + + existing = databases.list_rows(org_id, mid) + by_email = {str(r.get(main_email, "")).strip().lower(): r for r in existing if str(r.get(main_email, "")).strip()} + + added = updated = conflicts = 0 + for raw in incoming: + row = {rename.get(k, k): v for k, v in raw.items() if k != "row_id"} + email = str(row.get(main_email, "") or "").strip().lower() + person = by_email.get(email) if email else None + if person is None: + row[TAGS] = _add_tag(str(row.get(TAGS, "") or ""), tag) + row_id = uuid.uuid4().hex + db.set_doc(databases._row_path(org_id, mid, row_id), {"encrypted_data": encrypt(json.dumps(row))}) + if email: + by_email[email] = row | {"row_id": row_id} + added += 1 + continue + changed = False + for k, v in row.items(): + if k in (TAGS, main_email) or v in (None, ""): + continue + current = person.get(k) + if str(current or "").strip() == "": + person[k] = v + changed = True + elif not _same(current, v): + _record_conflict(org_id, person["row_id"], email, k, + {"value": current, "source": "Earlier", "at": ""}, + {"value": v, "source": tag, "at": _now()}) + person[k] = v + changed = True + conflicts += 1 + tags = _add_tag(str(person.get(TAGS, "") or ""), tag) + incoming_tags = str(row.get(TAGS, "") or "") + for t in split_items(incoming_tags, ";"): + tags = _add_tag(tags, t) + if tags != (person.get(TAGS) or ""): + person[TAGS] = tags + changed = True + if changed: + data = {k: v for k, v in person.items() if k != "row_id"} + db.set_doc(databases._row_path(org_id, mid, person["row_id"]), {"encrypted_data": encrypt(json.dumps(data))}) + updated += 1 + + db.update_doc(databases._database_path(org_id, mid), { + "columns": columns, + "row_count": len(existing) + added, + }) + if conflicts: + _recount_conflicts(org_id, mid) + return {"database_id": mid, "added": added, "updated": updated, "conflicts": conflicts} + + +# --- Audiences ----------------------------------------------------------------------- + +def _clean_conditions(conditions: list[dict]) -> list[dict]: + out = [] + for c in conditions or []: + field, op = str(c.get("field", "")).strip(), str(c.get("op", "")).strip() + if field and op: + out.append({"field": field, "op": op, "value": str(c.get("value", ""))}) + return out + + +def _tag_conditions(tag: str) -> list[dict]: + return [{"field": TAGS, "op": "has_tag", "value": tag}] + + +def _ensure_tag_audience(org_id: str, tag: str) -> None: + """An upload or a folded sheet gets an audience of the same name, unless one exists.""" + for a in _audience_docs(org_id).values(): + if a.get("conditions") == _tag_conditions(tag) or a.get("name", "").lower() == tag.lower(): + return + db.set_doc(_audience_path(org_id, uuid.uuid4().hex), { + "name": tag, "conditions": _tag_conditions(tag), "created_at": _now(), "count": 0, + }) + + +def _audience_docs(org_id: str) -> dict[str, dict]: + prefix = f"orgs/{org_id}/audiences/" + return {path[len(prefix):]: data for path, data in db.query_prefix(prefix).items()} + + +def list_audiences(org_id: str, actor_uid: str) -> list[dict]: + """Every audience with how many people it holds now. The counts are stored back so the + dashboard can show them without reading the sheet again.""" + orgs.require_permission(org_id, actor_uid) + hub = refresh(org_id) + if is_split(hub): + sheets = dict(_spokes(org_id)) + return [{"audience_id": aid, "name": a["name"], "database_id": a["database_id"], "conditions": [], "count": a.get("count", 0), + "rows": sheets[a["database_id"]].get("row_count", 0), "created_at": a.get("created_at")} + for aid, a in sorted(_audience_docs(org_id).items(), key=lambda kv: kv[1].get("created_at", "")) + if a.get("database_id") in sheets] + docs = _audience_docs(org_id) + mid = main_id(org_id) + rows, columns = [], [] + if mid and docs: + columns = databases.get_database(org_id, mid)["columns"] + rows = databases.list_rows(org_id, mid) + out = [] + for aid, a in sorted(docs.items(), key=lambda kv: kv[1].get("created_at", "")): + count = len(databases.apply_segment(rows, columns, a.get("conditions") or [])) if mid else 0 + if count != a.get("count"): + db.update_doc(_audience_path(org_id, aid), {"count": count}) + out.append({"audience_id": aid, "name": a["name"], "conditions": a.get("conditions") or [], "count": count, "created_at": a.get("created_at")}) + return out + + +def create_audience(org_id: str, actor_uid: str, name: str, conditions: list[dict]) -> str: + orgs.require_permission(org_id, actor_uid, "edit_lists") + if not needs_split(org_id): + return new_audience_sheet(org_id, actor_uid, name) + name = name.strip() + if not name: + raise databases.ValidationError("Give the audience a name.") + if name.lower() == MAIN_NAME.lower() or any(a.get("name", "").lower() == name.lower() for a in _audience_docs(org_id).values()): + raise databases.ValidationError("An audience with that name already exists.") + aid = uuid.uuid4().hex + db.set_doc(_audience_path(org_id, aid), {"name": name, "conditions": _clean_conditions(conditions), "created_at": _now(), "count": 0}) + return aid + + +def update_audience(org_id: str, actor_uid: str, audience_id: str, name: str | None, conditions: list[dict] | None) -> None: + orgs.require_permission(org_id, actor_uid, "edit_lists") + if db.get_doc(_audience_path(org_id, audience_id)) is None: + raise orgs.NotFoundError("That audience no longer exists.") + patch: dict = {} + if name is not None: + if not name.strip(): + raise databases.ValidationError("Give the audience a name.") + patch["name"] = name.strip() + sheet_id = (db.get_doc(_audience_path(org_id, audience_id)) or {}).get("database_id") + if sheet_id: + db.update_doc(databases._database_path(org_id, sheet_id), {"name": name.strip()}) + mark_stale(org_id) + if conditions is not None: + patch["conditions"] = _clean_conditions(conditions) + if patch: + db.update_doc(_audience_path(org_id, audience_id), patch) + + +def delete_audience(org_id: str, actor_uid: str, audience_id: str) -> None: + """Removes the audience. Its own sheet is archived, not deleted, so past campaigns still + show it; people in no other audience leave Everyone.""" + orgs.require_permission(org_id, actor_uid, "edit_lists") + sheet_id = (db.get_doc(_audience_path(org_id, audience_id)) or {}).get("database_id") + db.delete_doc(_audience_path(org_id, audience_id)) + if sheet_id: + db.update_doc(databases._database_path(org_id, sheet_id), {"archived": True}) + mark_stale(org_id) + + +# --- Uploads and folding old sheets ------------------------------------------------------ + +def upload(org_id: str, actor_uid: str, tag: str, file_bytes: bytes, filename: str) -> dict: + """Reads a spreadsheet into the main sheet, tagging everyone in it with `tag`. Once each + audience has its own sheet, the file becomes (or adds to) that audience's sheet instead.""" + orgs.require_permission(org_id, actor_uid, "edit_lists") + if not needs_split(org_id): + return upload_sheet(org_id, actor_uid, tag, file_bytes, filename, None) + tag = tag.strip() + if not tag: + raise databases.ValidationError("Name this upload; it becomes the audience name.") + ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else "" + parser = databases._PARSERS.get(ext) + if parser is None: + raise databases.ValidationError(f"Unsupported file type {filename!r}. Use .csv, .xlsx or .json.") + headers, rows = parser(file_bytes) + headers, rows = databases._clean(headers, rows) + if not headers or not rows: + raise databases.ValidationError("No usable data found in that file.") + columns = [] + for h in headers: + values = [r.get(h, "") for r in rows] + col = {"name": h, "type": databases.classify_column(h, values)} + if col["type"] == "tag": + col["delimiter"] = databases.detect_list_delimiter(values) or ";" + columns.append(col) + result = _upsert(org_id, rows, columns, tag) + _ensure_tag_audience(org_id, tag) + return result + + +def combine_sheets(org_id: str, actor_uid: str) -> dict: + """Folds every separate sheet into the main one, once. Each person is tagged with the + sheet they came from and each sheet becomes an audience of the same name. The old sheets + stay, marked archived, so past campaigns keep their list names.""" + orgs.require_permission(org_id, actor_uid, "edit_lists") + sheets = [(did, d) for did, d in databases.list_databases(org_id).items() if not d.get("is_main") and not d.get("archived") and not d.get("spoke")] + if not needs_split(org_id): + # Each sheet stays as it is and becomes an audience; Everyone is built from them. + mid = main_id(org_id) or _create_split_hub(org_id) + for did, sheet in sheets: + db.update_doc(databases._database_path(org_id, did), {"spoke": True}) + _link_audience(org_id, sheet["name"], did) + refresh(org_id, force=True) + return {"database_id": mid, "sheets": len(sheets), "added": 0, "updated": 0} + added = updated = 0 + for did, sheet in sorted(sheets, key=lambda kv: kv[1].get("created_at", "")): + rows = _full_rows(org_id, did, sheet) + r = _upsert(org_id, rows, sheet.get("columns") or [], sheet["name"]) + added += r["added"] + updated += r["updated"] + _ensure_tag_audience(org_id, sheet["name"]) + db.update_doc(databases._database_path(org_id, did), {"archived": True, "combined_at": _now()}) + mid = main_id(org_id) or _create_main(org_id) + return {"database_id": mid, "sheets": len(sheets), "added": added, "updated": updated} + + +# --- Each audience is its own sheet ---------------------------------------------------- +# +# Once a workbook is split (the main sheet has `split: True`), every audience is a sheet of its +# own (`spoke: True`) that keeps exactly what people typed, one row per entry: a form filled in +# twice gives two rows. Everyone is rebuilt from those sheets: one row per email address with +# the audiences the person is in, when they were first added and where from. Everyone's rows +# also carry each field's newest answer (or the one someone picked), which is what a send to +# Everyone uses; the sheet shows only the four columns above. +# +# A write to any sheet marks Everyone stale; it is rebuilt the next time it is read or sent to. + +AUDIENCES = "Audiences" +ADDED = "Added" +SOURCE = "Source" +HUB_COLUMNS = [ + {"name": EMAIL, "type": "email", "flagged_row_ids": []}, + {"name": AUDIENCES, "type": "tag", "delimiter": ";", "flagged_row_ids": []}, + {"name": ADDED, "type": "date", "flagged_row_ids": []}, + {"name": SOURCE, "type": "text", "flagged_row_ids": []}, +] +_HUB_NAMES = {c["name"] for c in HUB_COLUMNS} + + +def is_split(hub: dict | None) -> bool: + return bool(hub and hub.get("is_main") and hub.get("split")) + + +def _hub(org_id: str) -> tuple[str | None, dict | None]: + for did, data in databases.list_databases(org_id).items(): + if data.get("is_main"): + return did, data + return None, None + + +def mark_stale(org_id: str) -> None: + """Called after anything changes a sheet's rows, so Everyone is rebuilt before it is next + read or sent to. Cheap: one read of the org's sheet list and at most one write.""" + mid, hub = _hub(org_id) + if is_split(hub) and not hub.get("stale"): + db.update_doc(databases._database_path(org_id, mid), {"stale": True}) + + +def _field_key(col: dict) -> str: + return " ".join(str(col.get("label") or col["name"]).split()).lower() + + +def _spokes(org_id: str) -> list[tuple[str, dict]]: + items = [(did, d) for did, d in databases.list_databases(org_id).items() if d.get("spoke") and not d.get("archived")] + return sorted(items, key=lambda kv: kv[1].get("created_at", "")) + + +def _people(org_id: str) -> tuple[dict[str, dict], list[dict]]: + """Everyone across every audience sheet, keyed by lower-case email: + {email: {email, audiences, added, source, answers: {field key: [(value, at, sheet)]}}}, + plus every field seen, in first-seen order, under the name it was first given.""" + people: dict[str, dict] = {} + fields: dict[str, dict] = {} + for did, sheet in _spokes(org_id): + columns = sheet.get("columns") or [] + ecol = _email_column(columns) + if not ecol: + continue + for col in columns: + key = _field_key(col) + if col["name"] != ecol and key not in fields and col["name"] not in _HUB_NAMES: + fields[key] = {k: v for k, v in col.items() if k not in ("flagged_row_ids", "label")} | { + "name": col.get("label") or col["name"], "flagged_row_ids": []} + fallback = sheet.get("created_at", "") + for row in _full_rows(org_id, did, sheet): + raw = str(row.get(ecol, "") or "").strip() + email = raw.lower() + if not databases.EMAIL_RE.match(email): + continue + at = databases.row_added_at(row["row_id"], fallback) + p = people.get(email) + if p is None: + p = people[email] = {"email": raw, "audiences": [], "added": at, "source": sheet["name"], "answers": {}} + if sheet["name"] not in p["audiences"]: + p["audiences"].append(sheet["name"]) + if at and (not p["added"] or at < p["added"]): + p["added"], p["source"] = at, sheet["name"] + for col in columns: + if col["name"] == ecol: + continue + v = row.get(col["name"]) + if v in (None, "") or isinstance(v, (dict, list)): + continue + p["answers"].setdefault(_field_key(col), []).append((str(v), at, sheet["name"])) + return people, list(fields.values()) + + +def _distinct(answers: list[tuple[str, str, str]]) -> list[dict]: + """One entry per different answer, keeping the newest time each was given, oldest first.""" + out: list[dict] = [] + for value, at, source in sorted(answers, key=lambda a: a[1] or ""): + same = next((x for x in out if _same(x["value"], value)), None) + if same is None: + out.append({"value": value, "source": source, "at": at}) + else: + same.update({"value": value, "source": source, "at": at}) + return sorted(out, key=lambda x: x["at"] or "") + + +def _spoke_conflict_path(org_id: str, email: str, key: str) -> str: + return f"orgs/{org_id}/conflicts/{hashlib.sha256(f'{email}|{key}'.encode()).hexdigest()[:32]}" + + +def refresh(org_id: str, force: bool = False) -> dict | None: + """Rebuilds Everyone from the audience sheets when something changed (or `force`). Keeps + each person's row id, writes only rows that changed, removes people no longer in any sheet + and updates the different-answers flags. Returns the main sheet's record.""" + mid, hub = _hub(org_id) + if not is_split(hub) or (not force and not hub.get("stale")): + return hub + # Cleared first: a write that lands while this runs marks it stale again. + db.update_doc(databases._database_path(org_id, mid), {"stale": False}) + people, fields = _people(org_id) + by_key = {_field_key(f): f["name"] for f in fields} + existing = {str(r.get(EMAIL, "")).strip().lower(): r for r in databases.list_rows(org_id, mid)} + flags = {path: d for path, d in db.query_prefix(f"orgs/{org_id}/conflicts/").items()} + seen_flags: set[str] = set() + open_flags = 0 + + for email, p in people.items(): + row = {EMAIL: p["email"], AUDIENCES: "; ".join(p["audiences"]), ADDED: (p["added"] or "")[:10], SOURCE: p["source"]} + for key, answers in p["answers"].items(): + name = by_key.get(key) + if not name: + continue + distinct = _distinct(answers) + value = distinct[-1]["value"] + if len(distinct) > 1: + path = _spoke_conflict_path(org_id, email, key) + seen_flags.add(path) + doc = flags.get(path) + known = [v["value"] for v in (doc or {}).get("values") or []] + new = any(not any(_same(v["value"], k) for k in known) for v in distinct) + if doc is None or new or doc.get("values") != distinct: + keep = bool(doc and doc.get("resolved") and not new) + db.set_doc(path, { + "email": email, "field": name, "key": key, "row_id": "", "values": distinct, + "created_at": (doc or {}).get("created_at") or _now(), "resolved": keep, + "chosen": (doc or {}).get("chosen", "") if keep else "", + "resolved_by": (doc or {}).get("resolved_by", "") if keep else "", + "resolved_at": (doc or {}).get("resolved_at", "") if keep else "", + }) + doc = {"resolved": keep, "chosen": (doc or {}).get("chosen", "") if keep else ""} + if doc.get("resolved") and doc.get("chosen"): + value = doc["chosen"] + else: + open_flags += 1 + row[name] = value + current = existing.pop(email, None) + if current is None: + db.set_doc(databases._row_path(org_id, mid, databases.new_row_id()), {"encrypted_data": encrypt(json.dumps(row))}) + elif {k: v for k, v in current.items() if k != "row_id"} != row: + db.set_doc(databases._row_path(org_id, mid, current["row_id"]), {"encrypted_data": encrypt(json.dumps(row))}) + for gone in existing.values(): + db.delete_doc(databases._row_path(org_id, mid, gone["row_id"])) + for path, d in flags.items(): + if "key" in d and path not in seen_flags: + db.delete_doc(path) # the answers agree now, or the person left every sheet + + counts = {} + for p in people.values(): + for name in p["audiences"]: + counts[name.lower()] = counts.get(name.lower(), 0) + 1 + sheet_names = {did: d["name"] for did, d in _spokes(org_id)} + for aid, a in _audience_docs(org_id).items(): + name = sheet_names.get(a.get("database_id") or "") + if name is not None: + count = counts.get(name.lower(), 0) + if a.get("count") != count or a.get("name") != name: + db.update_doc(_audience_path(org_id, aid), {"count": count, "name": name}) + + patch = {"columns": HUB_COLUMNS, "fields": fields, "row_count": len(people), "open_conflicts": open_flags, + "refreshed_at": _now()} + db.update_doc(databases._database_path(org_id, mid), patch) + return databases.get_database(org_id, mid) + + +def for_sending(org_id: str, database_id: str, database: dict) -> dict: + """The sheet as a send sees it. For Everyone: rebuilt if needed, with every field anyone + gave, so {First name} works in an email to everyone.""" + if not is_split(database): + return database + hub = refresh(org_id) or database + return hub | {"columns": HUB_COLUMNS + [f for f in hub.get("fields") or [] if f["name"] not in _HUB_NAMES]} + + +def latest_per_person(rows: list[dict], email_column: str | None) -> list[dict]: + """One row per address: the newest entry, so someone who filled a form in twice gets one + email that uses their latest answers. Rows without an address are left out.""" + if not email_column: + return [] + best: dict[str, dict] = {} + order: list[str] = [] + for row in rows: + email = str(row.get(email_column) or "").strip().lower() + if not email: + continue + if email not in best: + order.append(email) + best[email] = row + elif row["row_id"] > best[email]["row_id"] and row["row_id"].startswith("t"): + best[email] = row + return [best[e] for e in order] + + +def _new_sheet(org_id: str, name: str, columns: list[dict], rows: list[dict], source: str = "workbook") -> str: + did = uuid.uuid4().hex + cols = [({k: v for k, v in c.items() if k != "flagged_row_ids"} | {"flagged_row_ids": []}) for c in columns] + if not _email_column(cols): + cols.insert(0, {"name": EMAIL, "type": "email", "flagged_row_ids": []}) + db.set_doc(databases._database_path(org_id, did), { + "name": name, "spoke": True, "source_filename": "", "source_kind": source, "created_at": _now(), + "row_count": len(rows), "columns": cols, "lookup_tables": [], "suggestions": [], + }) + for row in rows: + db.set_doc(databases._row_path(org_id, did, databases.new_row_id()), + {"encrypted_data": encrypt(json.dumps({k: v for k, v in row.items() if k != "row_id"}))}) + return did + + +def _link_audience(org_id: str, name: str, database_id: str) -> str: + for aid, a in _audience_docs(org_id).items(): + if a.get("database_id") == database_id: + return aid + aid = uuid.uuid4().hex + db.set_doc(_audience_path(org_id, aid), {"name": name, "database_id": database_id, "conditions": [], "created_at": _now(), "count": 0}) + return aid + + +def _create_split_hub(org_id: str) -> str: + mid = _create_main(org_id) + db.update_doc(databases._database_path(org_id, mid), {"split": True, "columns": HUB_COLUMNS, "fields": [], "stale": True}) + return mid + + +def needs_split(org_id: str) -> bool: + _, hub = _hub(org_id) + return bool(hub) and not is_split(hub) + + +def split(org_id: str, actor_uid: str) -> dict: + """Gives every audience its own sheet, once, when the owner asks. Sheets that were combined + earlier come back as they were typed; people added to Everyone since go into the sheet of + their audience. Everyone is copied to an archived backup first and then keeps only email, + audiences, date added and source. Nothing is deleted.""" + orgs.require_permission(org_id, actor_uid, "edit_lists") + mid, hub = _hub(org_id) + if hub is None: + raise orgs.NotFoundError("There is no Everyone sheet yet.") + if is_split(hub): + return {"sheets": 0} + main_email = _email_column(hub["columns"]) or EMAIL + hub_rows = databases.list_rows(org_id, mid) + hub_cols = [c for c in hub["columns"] if c["name"] not in (TAGS,)] + + backup_id = databases.duplicate_database(org_id, actor_uid, mid, f"{MAIN_NAME} backup {_now()[:10]}") + db.update_doc(databases._database_path(org_id, backup_id), {"is_main": False, "archived": True, "backup": True}) + + sheets = databases.list_databases(org_id) + archived = {d["name"].strip().lower(): (did, d) for did, d in sheets.items() + if d.get("archived") and not d.get("backup") and not d.get("is_main") and did != backup_id} + made = 0 + placed: set[str] = set() # hub row ids now in at least one sheet + + def strip(row: dict) -> dict: + return {k: v for k, v in row.items() if k not in (TAGS, "row_id")} + + for aid, a in sorted(_audience_docs(org_id).items(), key=lambda kv: kv[1].get("created_at", "")): + conditions = a.get("conditions") or [] + tag = conditions[0]["value"] if conditions == _tag_conditions(conditions[0]["value"] if conditions else "") else None + members = databases.apply_segment(hub_rows, hub["columns"], conditions) if conditions else [] + placed.update(r["row_id"] for r in members) + old = archived.pop(tag.strip().lower(), None) if tag else None + if old: + did, sheet = old + db.update_doc(databases._database_path(org_id, did), {"archived": False, "spoke": True, "combined_at": ""}) + sheet_email = _email_column(sheet.get("columns") or []) + have = {str(r.get(sheet_email, "")).strip().lower() for r in databases.list_rows(org_id, did)} if sheet_email else set() + extra = [strip(r) for r in members if str(r.get(main_email, "")).strip().lower() not in have] + for row in extra: + if sheet_email and sheet_email != main_email: + row[sheet_email] = row.pop(main_email, "") + databases.insert_row(org_id, did, row) + else: + did = _new_sheet(org_id, a["name"], hub_cols, [strip(r) for r in members]) + db.update_doc(_audience_path(org_id, aid), {"database_id": did, "conditions": [], "name": a["name"]}) + made += 1 + + # People in Everyone who are in no audience keep a sheet of their own. + loose = [strip(r) for r in hub_rows if r["row_id"] not in placed] + if loose: + did = _new_sheet(org_id, "Added to Everyone", hub_cols, loose) + _link_audience(org_id, "Added to Everyone", did) + made += 1 + + # Sign-up forms keep adding to the sheet they used; a form that pointed at Everyone gets + # a sheet named after it, and a form on an old sheet brings that sheet back. + prefix = f"orgs/{org_id}/collect_keys/" + for path, key in db.query_prefix(prefix).items(): + target = key.get("database_id") + if target == mid: + name = key.get("name") or "Sign-ups" + did = _new_sheet(org_id, name, [{"name": EMAIL, "type": "email"}], []) + _link_audience(org_id, name, did) + db.update_doc(path, {"database_id": did}) + made += 1 + else: + for nm, (did, sheet) in list(archived.items()): + if did == target: + db.update_doc(databases._database_path(org_id, did), {"archived": False, "spoke": True}) + _link_audience(org_id, sheet["name"], did) + archived.pop(nm) + made += 1 + + # Flags from before were keyed to Everyone's rows; the rebuild raises them again from the sheets. + for path, d in db.query_prefix(f"orgs/{org_id}/conflicts/").items(): + if "key" not in d: + db.delete_doc(path) + db.update_doc(databases._database_path(org_id, mid), {"split": True, "stale": True, "columns": HUB_COLUMNS}) + refresh(org_id, force=True) + return {"sheets": made, "backup_id": backup_id} + + +def new_audience_sheet(org_id: str, actor_uid: str, name: str) -> str: + """An empty audience with its own sheet, ready for people to be added by hand or a form.""" + orgs.require_permission(org_id, actor_uid, "edit_lists") + name = name.strip() + if not name: + raise databases.ValidationError("Give the audience a name.") + if name.lower() == MAIN_NAME.lower() or any(a.get("name", "").lower() == name.lower() for a in _audience_docs(org_id).values()): + raise databases.ValidationError("An audience with that name already exists.") + if not main_id(org_id): + _create_split_hub(org_id) + did = _new_sheet(org_id, name, [{"name": EMAIL, "type": "email"}], []) + aid = _link_audience(org_id, name, did) + mark_stale(org_id) + return aid + + +# Column labels: every column of an uploaded file gets one, so the same thing is matched +# across sheets whatever each file called it. +LABELS = [ + "Email", "First name", "Last name", "Full name", "Phone", "Organisation", "Job title", + "Institution", "Course", "Level", "City", "State", "Country", "Address", "Date of birth", + "Gender", "Website", "ID number", "Date", "Notes", +] +_LABEL_HINTS = [ + ("Email", ("email", "e-mail", "mail address")), + ("First name", ("first name", "firstname", "given name", "forename")), + ("Last name", ("last name", "lastname", "surname", "family name")), + ("Full name", ("full name", "fullname", "name of", "your name", "names", "name")), + ("Phone", ("phone", "mobile", "whatsapp", "tel", "contact number", "gsm")), + ("Organisation", ("organisation", "organization", "company", "business", "employer")), + ("Job title", ("job", "title", "role", "position", "occupation")), + ("Institution", ("institution", "university", "school", "college", "polytechnic")), + ("Course", ("course", "department", "programme", "program", "faculty", "major")), + ("Level", ("level", "year of study", "class")), + ("City", ("city", "town")), + ("State", ("state", "region", "province")), + ("Country", ("country", "nationality")), + ("Address", ("address", "street")), + ("Date of birth", ("birth", "dob")), + ("Gender", ("gender", "sex")), + ("Website", ("website", "url", "link")), + ("ID number", ("nin", "matric", "id number", "student id", "reg no", "registration")), + ("Date", ("date", "timestamp", "time")), +] + + +def suggest_label(header: str, col_type: str) -> str: + """A first guess at what a column holds. The person checks and changes every one.""" + h = " ".join(header.replace("_", " ").replace("-", " ").split()).lower() + if col_type == "email": + return "Email" + for label, hints in _LABEL_HINTS: + if h == label.lower() or any(hint in h for hint in hints): + return label + if col_type == "phone": + return "Phone" + if col_type == "date": + return "Date" + return header.strip() + + +def _mask(value: str, col_type: str) -> str: + """Enough of a value to recognise what the column is, without showing the whole thing.""" + v = str(value).strip() + if not v: + return "" + if col_type == "email" and "@" in v: + name, _, domain = v.partition("@") + return f"{name[:1]}โฆ@{domain}" + if col_type == "phone" or sum(ch.isdigit() for ch in v) >= 6: + return "".join("โข" if ch.isdigit() else ch for ch in v[:-2]) + v[-2:] + return v if len(v) <= 24 else v[:22] + "โฆ" + + +def _read_file(file_bytes: bytes, filename: str) -> tuple[list[str], list[dict], list[dict]]: + ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else "" + parser = databases._PARSERS.get(ext) + if parser is None: + raise databases.ValidationError(f"Unsupported file type {filename!r}. Use .csv, .xlsx or .json.") + headers, rows = parser(file_bytes) + headers, rows = databases._clean(headers, rows) + if not headers or not rows: + raise databases.ValidationError("No usable data found in that file.") + columns = [] + for h in headers: + values = [r.get(h, "") for r in rows] + col = {"name": h, "type": databases.classify_column(h, values)} + if col["type"] == "tag": + col["delimiter"] = databases.detect_list_delimiter(values) or ";" + columns.append(col) + return headers, rows, columns + + +def analyse_upload(org_id: str, actor_uid: str, file_bytes: bytes, filename: str) -> dict: + """The columns a file holds, each with a suggested label and a few masked examples, so the + person can label every one before anything is saved.""" + orgs.require_permission(org_id, actor_uid, "edit_lists") + _, rows, columns = _read_file(file_bytes, filename) + known = sorted({f["name"] for f in (_hub(org_id)[1] or {}).get("fields") or []} | set(LABELS) - {""}) + out = [] + for col in columns: + samples = [_mask(r.get(col["name"], ""), col["type"]) for r in rows if str(r.get(col["name"], "")).strip()][:3] + out.append({"name": col["name"], "type": col["type"], "label": suggest_label(col["name"], col["type"]), "samples": samples}) + return {"rows": len(rows), "columns": out, "labels": known} + + +def upload_sheet(org_id: str, actor_uid: str, name: str, file_bytes: bytes, filename: str, labels: dict[str, str] | None) -> dict: + """Saves a file as an audience's sheet, as typed. With an audience of that name already, the + file's rows are added to its sheet as new rows. `labels` maps each column to what it holds.""" + orgs.require_permission(org_id, actor_uid, "edit_lists") + name = name.strip() + if not name: + raise databases.ValidationError("Name this upload; it becomes the audience name.") + _, rows, columns = _read_file(file_bytes, filename) + if not _email_column(columns): + raise databases.ValidationError("This file has no column of email addresses.") + for col in columns: + label = str((labels or {}).get(col["name"]) or "").strip()[:60] + if label and label != col["name"]: + col["label"] = label + if not main_id(org_id): + _create_split_hub(org_id) + existing = next(((did, d) for did, d in _spokes(org_id) if d["name"].strip().lower() == name.lower()), None) + if existing: + did, sheet = existing + known = {c["name"] for c in sheet["columns"]} + cols = list(sheet["columns"]) + [c | {"flagged_row_ids": []} for c in columns if c["name"] not in known] + sheet_email, file_email = _email_column(sheet["columns"]), _email_column(columns) + for row in rows: + if sheet_email and file_email and sheet_email != file_email: + row[sheet_email] = row.pop(file_email, "") + db.set_doc(databases._row_path(org_id, did, databases.new_row_id()), {"encrypted_data": encrypt(json.dumps(row))}) + db.update_doc(databases._database_path(org_id, did), {"columns": cols, "row_count": sheet.get("row_count", 0) + len(rows)}) + added_to = True + else: + did = _new_sheet(org_id, name, columns, rows, source=filename.rsplit(".", 1)[-1].lower()) + db.update_doc(databases._database_path(org_id, did), {"source_filename": filename}) + added_to = False + aid = _link_audience(org_id, name, did) + mark_stale(org_id) + refresh(org_id) + return {"database_id": did, "audience_id": aid, "added": len(rows), "updated": 0, "existing": added_to} diff --git a/backend/worker.py b/backend/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..ddfabf704f202d4e9d5b8692d4164fdef6f472a1 --- /dev/null +++ b/backend/worker.py @@ -0,0 +1,61 @@ +""" +The sending worker: delivers queued sends from a machine that can reach mail servers. + +The hosted app (Hugging Face Space) runs with SEND_ON_THIS_SERVER=false, so it only saves sends +as queued. This worker, run on a computer that can reach mail servers, picks them up: + + python -m backend.worker + +It checks for waiting sends every 5 minutes and runs the slower checks (automations, delivery) +every 30 minutes. A shared lease stops two machines from sending the same message twice. +Sends only go out while this is running. +""" + +from __future__ import annotations + +import logging +import os +import threading +import time + +from backend import api_access, local_store, sending, timing + +log = logging.getLogger("m8ion.worker") + +SEND_EVERY = float(os.getenv("WORKER_SEND_EVERY", "300")) # beta: fewer database reads; sends start within 5 minutes +FULL_EVERY = float(os.getenv("WORKER_FULL_EVERY", "1800")) +BUDGET = 240 # seconds of sending per pass +CHECK_IN_EVERY = 120 # tells the app the worker is running (see sending.sender_status) + + +def run(stop: threading.Event | None = None) -> None: + stop = stop or threading.Event() + local_store.init_local_store(os.getenv("LOCAL_STORE_DB_PATH", "local_store.db")) + last_full = -FULL_EVERY + last_seen = -CHECK_IN_EVERY + log.info("Sending worker started. Checking every %.0f seconds. Press Ctrl+C to stop.", SEND_EVERY) + while not stop.is_set(): + try: + if time.monotonic() - last_seen >= CHECK_IN_EVERY: + sending.worker_checked_in() + last_seen = time.monotonic() + if time.monotonic() - last_full >= FULL_EVERY: + result = timing.run_due(budget_seconds=BUDGET) + last_full = time.monotonic() + else: + result = {"sends": sending.run_due(budget_seconds=BUDGET)} + if api_access.run_queued(): + log.info("Delivered waiting API messages") + if result["sends"]["checked"]: + log.info("Worked on %s send(s)", result["sends"]["checked"]) + except Exception: # one bad pass must not stop the worker + log.exception("A pass failed; trying again shortly") + stop.wait(SEND_EVERY) + + +if __name__ == "__main__": + logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s", datefmt="%H:%M:%S") + try: + run() + except KeyboardInterrupt: + log.info("Sending worker stopped.") diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..b53c9911d04ae63898a182add0086ca37b279ebc --- /dev/null +++ b/requirements.txt @@ -0,0 +1,14 @@ +# Phase 1 prototype โ grows as the real backend (FastAPI, GCP KMS client, Firebase Admin, +# etc.) gets built. Kept minimal for now: just what's needed to run the test suite. +pytest>=8.0 +python-dotenv>=1.0 +cryptography>=42.0 +fastapi>=0.110 +uvicorn>=0.29 +httpx>=0.27 +firebase-admin>=6.5 +python-multipart>=0.0.9 +openpyxl>=3.1 +Pillow>=10.1 +tzdata>=2024.1 # time zones on Windows; Linux has them built in +psycopg[binary]>=3.1 # read-only connections to outside Postgres / Supabase databases