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..563980c20be74970b5472a59e3ca0af9336a91d5 --- /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. LOCAL_TICKER runs the send timer here. +ENV LOCAL_STORE_DB_PATH=/tmp/local_store.db LOCAL_TICKER=true 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/app.py b/backend/app.py new file mode 100644 index 0000000000000000000000000000000000000000..f0ecab588198e682b54b2e0a90e20d52fb77a3aa --- /dev/null +++ b/backend/app.py @@ -0,0 +1,1007 @@ +""" +The HTTP layer. Auth goes through backend.auth.current_uid โ a real Firebase ID token +(REAL_AUTH_ENABLED=true) or the X-Dev-Uid header bypass (false, the default in tests โ see +tests/conftest.py). Only exposes what the built screens actually need โ grows as more +screens are built, not speculatively ahead of them. +""" + +from __future__ import annotations + +import hmac +import logging +import os +import sys +import threading +from contextlib import asynccontextmanager +from pathlib import Path + +from fastapi import BackgroundTasks, Depends, FastAPI, File, Form, Header, HTTPException, UploadFile +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel + +from backend import accounts, automations, brands, delivery, dns_check, identity, invites, collect, customizations, databases, local_store, mailboxes, orgs, overview, presets, sending, settings, storage, timing, unsubscribe +from backend.auth import current_email, current_uid, lookup_user +from backend import staff, verification +from backend.core.constants import PERMISSIONS +from backend.collect_api import router as collect_router +from backend.unsubscribe_api import router as unsubscribe_router + + +def _tick(stop: threading.Event, every: float = 1800) -> None: + while not stop.wait(every): + try: + timing.run_due() + except Exception: # one bad run must not stop the timer + logging.getLogger("m8ion").exception("Scheduled run failed") + + +@asynccontextmanager +async def _lifespan(app: FastAPI): + # backend/tests/conftest.py does this per-test with a throwaway file; a real running + # process needs it done once, against a persistent file, before any request lands. + local_store.init_local_store(os.getenv("LOCAL_STORE_DB_PATH", "local_store.db")) + # Locally there is no cloud timer, so a small thread plays that part. In production a + # scheduler calls POST /internal/run-due instead and nothing stays running between calls. + stop = threading.Event() + if os.getenv("LOCAL_TICKER", "true" if "pytest" not in sys.modules else "false").lower() == "true": + threading.Thread(target=_tick, args=(stop,), daemon=True).start() + yield + stop.set() + + +app = FastAPI(title="M8ion API", lifespan=_lifespan) + +# The public sign-up endpoints (docs/blueprint/adr/0006) set their own per-key CORS headers. +app.include_router(collect_router) +app.include_router(unsubscribe_router) + +app.add_middleware( + CORSMiddleware, + # Dev-only: any localhost port, since the Vite dev server's port can shift if 5173 is + # already taken (strictPort: false in vite.config.ts). + allow_origin_regex=r"http://localhost:\d+", + # The deployed web app. FRONTEND_URL can list several addresses, separated by commas. + allow_origins=[o.strip().rstrip("/") for o in os.getenv("FRONTEND_URL", "").split(",") if o.strip()], + allow_methods=["*"], + allow_headers=["*"], +) + + +def member_uid(org_id: str, uid: str = Depends(current_uid)) -> str: + """current_uid, for routes under /orgs/{org_id}: refuses anyone outside the org. + Finer checks (what the person's role allows) happen in each feature module.""" + _map_errors(orgs.require_permission, org_id, uid) + _map_errors(accounts.check_org_access, uid, _map_errors(orgs.get_org, org_id)) + return uid + + +def org_only_uid(org_id: str, uid: str = Depends(member_uid)) -> str: + """member_uid, for the parts an individual's personal org doesn't have: team, roles, + invites, brands, organisation details and DNS. Refused on the server, not just hidden.""" + if accounts.is_personal(org_id): + raise HTTPException(status_code=403, detail="This is for organisation accounts") + return uid + + +def _map_errors(fn, *args, **kwargs): + try: + return fn(*args, **kwargs) + except orgs.NotFoundError as exc: + raise HTTPException(status_code=404, detail=str(exc)) from exc + except orgs.PermissionError_ as exc: + raise HTTPException(status_code=403, detail=str(exc)) from exc + except (mailboxes.ValidationError, databases.ValidationError, accounts.AccountError, ValueError) as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + + +# --- Account type ----------------------------------------------------------- + +class RegisterAccountBody(BaseModel): + account_type: str + plan: str | None = None + name: str = "" + + +@app.get("/account") +def get_account(uid: str = Depends(current_uid)): + """Which kind of account this is, so the app can send the person to the right area.""" + return accounts.describe(uid) + + +@app.post("/account") +def register_account(body: RegisterAccountBody, uid: str = Depends(current_uid)): + """Chooses the account type, once. After this nothing here can change it.""" + return _map_errors(accounts.register, uid, body.account_type, body.plan, body.name) + + +class IdentityBody(BaseModel): + values: dict[str, str] = {} + + +@app.get("/account/identity") +def get_identity(uid: str = Depends(current_uid)): + return _map_errors(identity.describe, uid) + + +@app.put("/account/identity") +def submit_identity(body: IdentityBody, uid: str = Depends(current_uid)): + return _map_errors(identity.submit, uid, body.values) + + +# --- Orgs ------------------------------------------------------------------- + +class CreateOrgBody(BaseModel): + name: str + + +@app.post("/orgs") +def create_org(body: CreateOrgBody, uid: str = Depends(current_uid)): + _map_errors(accounts.require_organization, uid) + accounts.ensure_organization(uid) + org_id = orgs.create_org(owner_uid=uid, name=body.name) + return {"org_id": org_id, "role": "owner"} + + +@app.get("/orgs") +def list_orgs(uid: str = Depends(current_uid)): + return [ + {"org_id": org_id, "role": role, "name": (org := orgs.get_org(org_id))["name"], + "kind": org.get("kind", "organization"), + "permissions": sorted(orgs.effective_permissions(org_id, uid))} + for org_id, role in orgs.list_orgs_for_user(uid).items() + ] + + +# --- Mailbox connections ------------------------------------------------------ + +class ConnectMailboxBody(BaseModel): + kind: str + credentials: dict + + +def _public_mailbox(connection_id: str, data: dict) -> dict: + """Drops encrypted_credentials โ the API has no business returning that blob at all, + encrypted or not.""" + return {"connection_id": connection_id, **{k: v for k, v in data.items() if k != "encrypted_credentials"}} + + +@app.post("/orgs/{org_id}/mailboxes") +def connect_mailbox(org_id: str, body: ConnectMailboxBody, uid: str = Depends(member_uid)): + connection_id = _map_errors(mailboxes.connect_mailbox, org_id, uid, body.kind, body.credentials) + return _public_mailbox(connection_id, mailboxes.get_mailbox(org_id, connection_id)) + + +@app.post("/orgs/{org_id}/mailboxes/{connection_id}/verify") +def verify_mailbox(org_id: str, connection_id: str, uid: str = Depends(member_uid)): + _map_errors(orgs.require_permission, org_id, uid, "manage_mailboxes") + status = _map_errors(mailboxes.verify_mailbox, org_id, connection_id) + connection = mailboxes.get_mailbox(org_id, connection_id) + return {"connection_id": connection_id, "status": status, "status_message": connection["status_message"]} + + +class DismissMailboxBody(BaseModel): + dismissed: bool = True + + +@app.post("/orgs/{org_id}/mailboxes/{connection_id}/dismiss") +def dismiss_mailbox(org_id: str, connection_id: str, body: DismissMailboxBody, uid: str = Depends(member_uid)): + _map_errors(mailboxes.set_dismissed, org_id, uid, connection_id, body.dismissed) + return {"connection_id": connection_id, "dismissed": body.dismissed} + + +@app.get("/orgs/{org_id}/mailboxes") +def list_mailboxes(org_id: str, uid: str = Depends(member_uid)): + return [_public_mailbox(cid, data) for cid, data in mailboxes.list_mailboxes(org_id).items()] + + +@app.get("/orgs/{org_id}/mailboxes/{connection_id}") +def get_mailbox(org_id: str, connection_id: str, uid: str = Depends(member_uid)): + connection = _map_errors(mailboxes.get_mailbox, org_id, connection_id) + detail = _public_mailbox(connection_id, connection) | { + "settings": mailboxes.mailbox_settings(connection), + "sent_today": sending.sent_today(org_id, connection_id), + "next_credential_change": mailboxes.next_credential_change(connection), + } + if connection["kind"] == "smtp": + # Server details without the password, so the change form can start from them. + creds = mailboxes.get_decrypted_credentials(org_id, connection_id) + detail["smtp"] = {k: creds.get(k) for k in ("host", "port", "username")} + # The incoming side, also without its password. + detail["imap"] = { + "host": creds.get("imap_host") or "", + "port": creds.get("imap_port") or 993, + "username": creds.get("imap_username") or "", + } + return detail + + +class MailboxSettingsBody(BaseModel): + values: dict + + +@app.put("/orgs/{org_id}/mailboxes/{connection_id}/settings") +def update_mailbox_settings(org_id: str, connection_id: str, body: MailboxSettingsBody, uid: str = Depends(member_uid)): + return _map_errors(mailboxes.update_settings, org_id, uid, connection_id, body.values) + + +class MailboxCredentialsBody(BaseModel): + credentials: dict + + +@app.put("/orgs/{org_id}/mailboxes/{connection_id}/credentials") +def change_mailbox_credentials(org_id: str, connection_id: str, body: MailboxCredentialsBody, uid: str = Depends(member_uid)): + return _map_errors(mailboxes.change_credentials, org_id, uid, connection_id, body.credentials) + + +@app.delete("/orgs/{org_id}/mailboxes/{connection_id}") +def remove_mailbox(org_id: str, connection_id: str, uid: str = Depends(member_uid)): + _map_errors(mailboxes.remove_mailbox, org_id, uid, connection_id) + return {"ok": True} + + +# --- Audience databases ------------------------------------------------------- + +def _save_upload_copy(org_id: str, database_id: str, ext: str, file_bytes: bytes) -> None: + """Keeps the raw uploaded file, per the product requirement that an upload is never just + parsed-and-discarded. Supabase Storage when configured, a local folder otherwise.""" + try: + storage.save_upload(org_id, database_id, ext, file_bytes) + except storage.StorageError as err: + raise HTTPException(503, str(err)) from err + + +@app.post("/orgs/{org_id}/databases") +async def create_database( + org_id: str, name: str = Form(...), file: UploadFile = File(...), uid: str = Depends(member_uid), +): + file_bytes = await file.read() + database_id = _map_errors( + databases.create_database_from_upload, + org_id, uid, name, file_bytes, file.filename or "upload", + save_copy=lambda database_id, ext, data: _save_upload_copy(org_id, database_id, ext, data), + ) + return databases.get_database(org_id, database_id) | {"database_id": database_id} + + +@app.get("/orgs/{org_id}/databases") +def list_databases(org_id: str, uid: str = Depends(member_uid)): + return [{"database_id": did, **data} for did, data in databases.list_databases(org_id).items()] + + +@app.get("/orgs/{org_id}/databases/{database_id}") +def get_database(org_id: str, database_id: str, uid: str = Depends(member_uid)): + database = _map_errors(databases.get_database, org_id, database_id) + rows = databases.list_rows(org_id, database_id) + return {"database_id": database_id, **database, "rows": rows} + + +class AddRowBody(BaseModel): + values: dict + + +@app.post("/orgs/{org_id}/databases/{database_id}/rows") +def add_row(org_id: str, database_id: str, body: AddRowBody, uid: str = Depends(member_uid)): + row_id = _map_errors(databases.add_row, org_id, uid, database_id, body.values) + return {"row_id": row_id} + + +class BulkSetValuesBody(BaseModel): + updates: dict[str, dict] + + +# Registered BEFORE /rows/{row_id} below: Starlette matches path templates in registration +# order, and {row_id} would otherwise happily capture the literal segment "batch", silently +# routing every call here into update_row instead (misrouted to the wrong handler/body model, +# not a 404 โ caught via a 422 on the wrong required field, "tags", during manual testing). +@app.patch("/orgs/{org_id}/databases/{database_id}/rows/batch") +def bulk_set_values(org_id: str, database_id: str, body: BulkSetValuesBody, uid: str = Depends(member_uid)): + updated = _map_errors(databases.bulk_set_values, org_id, uid, database_id, body.updates) + return {"updated_row_ids": updated} + + +class UpdateRowBody(BaseModel): + tags: dict + + +@app.patch("/orgs/{org_id}/databases/{database_id}/rows/{row_id}") +def update_row(org_id: str, database_id: str, row_id: str, body: UpdateRowBody, uid: str = Depends(member_uid)): + _map_errors(databases.update_row, org_id, uid, database_id, row_id, body.tags) + return {"row_id": row_id} + + +class BulkUpdateRowsBody(BaseModel): + row_ids: list[str] + tags: dict + + +@app.patch("/orgs/{org_id}/databases/{database_id}/rows") +def bulk_update_rows(org_id: str, database_id: str, body: BulkUpdateRowsBody, uid: str = Depends(member_uid)): + updated = _map_errors(databases.bulk_update_rows, org_id, uid, database_id, body.row_ids, body.tags) + return {"updated_row_ids": updated} + + +class BulkAppendTagBody(BaseModel): + row_ids: list[str] + tag: str + tag_column: str = "Tags" + + +@app.post("/orgs/{org_id}/databases/{database_id}/rows/append-tag") +def bulk_append_tag(org_id: str, database_id: str, body: BulkAppendTagBody, uid: str = Depends(member_uid)): + updated = _map_errors( + databases.bulk_append_tag, org_id, uid, database_id, body.row_ids, body.tag, body.tag_column, + ) + return {"updated_row_ids": updated} + + +class DeleteRowsBody(BaseModel): + row_ids: list[str] + + +@app.post("/orgs/{org_id}/databases/{database_id}/rows/delete") +def delete_rows(org_id: str, database_id: str, body: DeleteRowsBody, uid: str = Depends(member_uid)): + deleted = _map_errors(databases.delete_rows, org_id, uid, database_id, body.row_ids) + return {"deleted": deleted} + + +@app.get("/orgs/{org_id}/databases/{database_id}/lookups/{lookup_name}") +def get_lookup_table(org_id: str, database_id: str, lookup_name: str, uid: str = Depends(member_uid)): + return _map_errors(databases.get_lookup_table, org_id, database_id, lookup_name) + + +class SegmentPreviewBody(BaseModel): + conditions: list[dict] + + +@app.post("/orgs/{org_id}/databases/{database_id}/segment-preview") +def preview_segment(org_id: str, database_id: str, body: SegmentPreviewBody, uid: str = Depends(member_uid)): + return _map_errors(databases.preview_segment, org_id, database_id, body.conditions) + + +class ColumnListBody(BaseModel): + delimiter: str | None = None # None dismisses the "this looks like a list" suggestion + + +@app.post("/orgs/{org_id}/databases/{database_id}/columns/{column}/list") +def set_column_list(org_id: str, database_id: str, column: str, body: ColumnListBody, uid: str = Depends(member_uid)): + _map_errors(databases.set_column_list, org_id, uid, database_id, column, body.delimiter) + return {"column": column, "delimiter": body.delimiter} + + +class RenderPreviewBody(BaseModel): + subject: str = "" + html_body: str = "" + segment: list[dict] = [] + index: int = 0 + email_column: str | None = None + + +@app.post("/orgs/{org_id}/databases/{database_id}/render-preview") +def render_preview(org_id: str, database_id: str, body: RenderPreviewBody, uid: str = Depends(member_uid)): + return _map_errors(sending.preview_render, org_id, database_id, body.subject, body.html_body, body.segment, body.index, body.email_column) + + +class UpdateColumnTypeBody(BaseModel): + type: str + + +@app.patch("/orgs/{org_id}/databases/{database_id}/columns/{column}") +def update_column_type(org_id: str, database_id: str, column: str, body: UpdateColumnTypeBody, uid: str = Depends(member_uid)): + flagged_row_ids = _map_errors(databases.update_column_type, org_id, database_id, column, body.type) + return {"column": column, "type": body.type, "flagged_row_ids": flagged_row_ids} + + +class RenameColumnBody(BaseModel): + name: str + + +@app.get("/orgs/{org_id}/databases/{database_id}/rename-suggestions") +def column_rename_suggestions(org_id: str, database_id: str, uid: str = Depends(member_uid)): + return {"suggestions": _map_errors(databases.column_rename_suggestions, org_id, database_id)} + + +@app.get("/orgs/{org_id}/databases/{database_id}/type-suggestions") +def column_type_suggestions(org_id: str, database_id: str, uid: str = Depends(member_uid)): + return {"suggestions": _map_errors(databases.column_type_suggestions, org_id, database_id)} + + +@app.post("/orgs/{org_id}/databases/{database_id}/columns/{column}/rename") +def rename_column(org_id: str, database_id: str, column: str, body: RenameColumnBody, uid: str = Depends(member_uid)): + name = _map_errors(databases.rename_column, org_id, uid, database_id, column, body.name) + return {"column": column, "name": name} + + +@app.delete("/orgs/{org_id}/databases/{database_id}/columns/{column}") +def remove_column(org_id: str, database_id: str, column: str, uid: str = Depends(member_uid)): + return _map_errors(databases.remove_column, org_id, uid, database_id, column) + + +class RestoreColumnBody(BaseModel): + column: dict + values_by_row_id: dict[str, str] + + +@app.post("/orgs/{org_id}/databases/{database_id}/columns/restore") +def restore_column(org_id: str, database_id: str, body: RestoreColumnBody, uid: str = Depends(member_uid)): + _map_errors(databases.restore_column, org_id, uid, database_id, body.column, body.values_by_row_id) + return {"column": body.column["name"]} + + +class RenameDatabaseBody(BaseModel): + name: str + + +@app.patch("/orgs/{org_id}/databases/{database_id}") +def rename_database(org_id: str, database_id: str, body: RenameDatabaseBody, uid: str = Depends(member_uid)): + _map_errors(databases.rename_database, org_id, uid, database_id, body.name) + return {"database_id": database_id, "name": body.name.strip()} + + +class SetDisabledBody(BaseModel): + disabled: bool + + +@app.post("/orgs/{org_id}/databases/{database_id}/disabled") +def set_database_disabled(org_id: str, database_id: str, body: SetDisabledBody, uid: str = Depends(member_uid)): + _map_errors(databases.set_database_disabled, org_id, uid, database_id, body.disabled) + return {"database_id": database_id, "disabled": body.disabled} + + +@app.delete("/orgs/{org_id}/databases/{database_id}") +def delete_database(org_id: str, database_id: str, uid: str = Depends(member_uid)): + _map_errors(databases.delete_database, org_id, uid, database_id) + return {"deleted": database_id} + + +class DuplicateDatabaseBody(BaseModel): + new_name: str + + +@app.post("/orgs/{org_id}/databases/{database_id}/duplicate") +def duplicate_database(org_id: str, database_id: str, body: DuplicateDatabaseBody, uid: str = Depends(member_uid)): + new_id = _map_errors(databases.duplicate_database, org_id, uid, database_id, body.new_name) + return databases.get_database(org_id, new_id) | {"database_id": new_id} + + +class MergeDatabasesBody(BaseModel): + database_id_a: str + database_id_b: str + new_name: str + + +@app.post("/orgs/{org_id}/databases/merge") +def merge_databases(org_id: str, body: MergeDatabasesBody, uid: str = Depends(member_uid)): + database_id = _map_errors( + databases.merge_databases, org_id, uid, body.database_id_a, body.database_id_b, body.new_name, + ) + return databases.get_database(org_id, database_id) | {"database_id": database_id} + + +# --- Customizations (saved header/footer/brand) --------------------------------- + +class CustomizationBody(BaseModel): + name: str + brand_color: str = "#c0392b" + logo_url: str = "" + header_text: str = "" + footer_html: str = "" + footer_bg: str = "#f4f4f4" + + +@app.get("/orgs/{org_id}/customizations") +def list_customizations(org_id: str, uid: str = Depends(member_uid)): + items = _map_errors(customizations.list_customizations, org_id, uid) + return [v | {"customization_id": k} for k, v in sorted(items.items(), key=lambda kv: kv[1]["name"].lower())] + + +@app.post("/orgs/{org_id}/customizations") +def create_customization(org_id: str, body: CustomizationBody, uid: str = Depends(member_uid)): + cid = _map_errors( + customizations.create_customization, org_id, uid, body.name, body.brand_color, + body.logo_url, body.header_text, body.footer_html, body.footer_bg, + ) + return customizations.get_customization(org_id, cid) | {"customization_id": cid} + + +@app.put("/orgs/{org_id}/customizations/{customization_id}") +def update_customization(org_id: str, customization_id: str, body: CustomizationBody, uid: str = Depends(member_uid)): + _map_errors( + customizations.update_customization, org_id, uid, customization_id, body.name, + body.brand_color, body.logo_url, body.header_text, body.footer_html, body.footer_bg, + ) + return customizations.get_customization(org_id, customization_id) | {"customization_id": customization_id} + + +@app.delete("/orgs/{org_id}/customizations/{customization_id}") +def delete_customization(org_id: str, customization_id: str, uid: str = Depends(member_uid)): + _map_errors(customizations.delete_customization, org_id, uid, customization_id) + return {"deleted": customization_id} + + +# --- Campaigns (manual send) --------------------------------------------------- + +class SendCampaignBody(BaseModel): + 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 + + +@app.post("/orgs/{org_id}/campaigns/send") +def send_campaign(org_id: str, body: SendCampaignBody, background: BackgroundTasks, uid: str = Depends(member_uid)): + send_id = _map_errors( + sending.queue_campaign, org_id, uid, body.subject, body.html_body, + body.mailbox_connection_id, body.database_id, body.segment, + body.attachments, body.certificate, body.email_column, body.mode, body.design, + body.scheduled_at, body.window, + ) + # The page gets its answer now; the emails go out in the background. + background.add_task(sending.process_send, org_id, send_id) + return sending.get_send(org_id, send_id) | {"send_id": send_id} + + +# --- Settings --------------------------------------------------------------------- + +class ProfileBody(BaseModel): + display_name: str = "" + job_title: str | None = None + phone: str | None = None + about: str | None = None + + +class OrgNameBody(BaseModel): + name: str + profile: dict | None = None + + +@app.get("/orgs/{org_id}/settings") +def get_settings(org_id: str, uid: str = Depends(member_uid)): + return _map_errors(settings.get_settings, org_id, uid) + + +@app.put("/orgs/{org_id}/settings/profile") +def update_profile(org_id: str, body: ProfileBody, uid: str = Depends(member_uid)): + return _map_errors(settings.update_profile, org_id, uid, body.display_name, body.model_dump(exclude={"display_name"}, exclude_none=True)) + + +@app.put("/orgs/{org_id}/settings/notifications") +def update_notifications(org_id: str, body: dict, uid: str = Depends(member_uid)): + return _map_errors(settings.update_notifications, org_id, uid, body) + + +@app.put("/orgs/{org_id}/settings/organisation") +def rename_org(org_id: str, body: OrgNameBody, uid: str = Depends(org_only_uid)): + return _map_errors(settings.rename_org, org_id, uid, body.name, body.profile) + + +@app.put("/orgs/{org_id}/settings/emails") +def update_email_settings(org_id: str, body: dict, uid: str = Depends(member_uid)): + return _map_errors(settings.update_emails, org_id, uid, body) + + +@app.get("/orgs/{org_id}/sends") +def list_sends(org_id: str, uid: str = Depends(member_uid)): + return _map_errors(sending.list_sends, org_id, uid) + + +@app.post("/orgs/{org_id}/sends/{send_id}/check-delivery") +def check_delivery(org_id: str, send_id: str, uid: str = Depends(member_uid)): + """Reads the mailbox's IMAP side now for delays, bounces and replies to this send.""" + _map_errors(orgs.require_permission, org_id, uid, "send") + return _map_errors(delivery.check_send, org_id, send_id) + + +@app.post("/orgs/{org_id}/sends/{send_id}/{action}") +def control_send(org_id: str, send_id: str, action: str, uid: str = Depends(member_uid)): + if action not in ("pause", "resume", "cancel"): + raise HTTPException(404, "Unknown action") + return _map_errors(sending.control_send, org_id, uid, send_id, action) + + +@app.get("/orgs/{org_id}/suppressions") +def list_suppressions(org_id: str, uid: str = Depends(member_uid)): + return _map_errors(unsubscribe.list_suppressed, org_id, uid) + + +class SuppressionBody(BaseModel): + email: str + + +@app.post("/orgs/{org_id}/suppressions") +def add_suppression(org_id: str, body: SuppressionBody, uid: str = Depends(member_uid)): + _map_errors(unsubscribe.add_by_hand, org_id, uid, body.email) + return {"email": body.email.strip().lower()} + + +@app.delete("/orgs/{org_id}/suppressions") +def remove_suppression(org_id: str, email: str, uid: str = Depends(member_uid)): + _map_errors(unsubscribe.remove, org_id, uid, email) + return {"removed": email} + + +class AutomationBody(BaseModel): + kind: str + name: str + mailbox_connection_id: str + database_id: str + email_column: str | None = None + segment: list[dict] | None = None + start_at: str | None = None + end_at: str | None = None + steps: list[dict] | None = None + subject: str | None = None + html_body: str | None = None + every: dict | None = None + date_column: str | None = None + offset_days: int = 0 + yearly: bool = False + + +@app.get("/orgs/{org_id}/automations") +def list_automations(org_id: str, uid: str = Depends(member_uid)): + return _map_errors(automations.list_for, org_id, uid) + + +@app.post("/orgs/{org_id}/automations") +def create_automation(org_id: str, body: AutomationBody, uid: str = Depends(member_uid)): + return _map_errors(automations.create, org_id, uid, body.model_dump()) + + +@app.post("/orgs/{org_id}/automations/{automation_id}/{action}") +def control_automation(org_id: str, automation_id: str, action: str, uid: str = Depends(member_uid)): + return _map_errors(automations.control, org_id, uid, automation_id, action) + + +@app.delete("/orgs/{org_id}/automations/{automation_id}") +def delete_automation(org_id: str, automation_id: str, uid: str = Depends(member_uid)): + _map_errors(automations.delete, org_id, uid, automation_id) + return {"deleted": automation_id} + + +@app.post("/internal/run-due") +def run_due(x_cron_secret: str = Header(default="")): + """Called by the cloud scheduler (every minute or so) to carry out what is due. Closed + unless CRON_SECRET is set, and the caller must send it.""" + secret = os.getenv("CRON_SECRET", "") + if not secret or not hmac.compare_digest(x_cron_secret, secret): + raise HTTPException(404, "Not found") + return timing.run_due() + + +@app.get("/orgs/{org_id}/sends/{send_id}") +def get_send_details(org_id: str, send_id: str, uid: str = Depends(member_uid)): + return _map_errors(sending.get_send_details, org_id, uid, send_id) + + +class CertificatePreviewBody(BaseModel): + database_id: str + certificate: dict + segment: list[dict] | None = None + index: int = 0 + email_column: str | None = None + + +@app.post("/orgs/{org_id}/certificates/preview") +def preview_certificate(org_id: str, body: CertificatePreviewBody, uid: str = Depends(member_uid)): + _map_errors(orgs.require_role, org_id, uid, "operator") + return _map_errors( + sending.preview_certificate, org_id, body.database_id, body.certificate, body.segment, body.index, body.email_column, + ) + + +# --- Presets (saved emails to start a campaign from) ---------------------------- + +class PresetBody(BaseModel): + name: str + subject: str = "" + mode: str + design: dict | None = None + html: str = "" + + +@app.get("/orgs/{org_id}/presets") +def list_presets(org_id: str, uid: str = Depends(member_uid)): + return _map_errors(presets.list_presets, org_id, uid) + + +@app.post("/orgs/{org_id}/presets") +def create_preset(org_id: str, body: PresetBody, uid: str = Depends(member_uid)): + preset_id = _map_errors(presets.create_preset, org_id, uid, body.name, body.subject, body.mode, body.design, body.html) + return presets.get_preset(org_id, preset_id) | {"preset_id": preset_id} + + +@app.put("/orgs/{org_id}/presets/{preset_id}") +def update_preset(org_id: str, preset_id: str, body: PresetBody, uid: str = Depends(member_uid)): + _map_errors(presets.update_preset, org_id, uid, preset_id, body.name, body.subject, body.mode, body.design, body.html) + return presets.get_preset(org_id, preset_id) | {"preset_id": preset_id} + + +@app.delete("/orgs/{org_id}/presets/{preset_id}") +def delete_preset(org_id: str, preset_id: str, uid: str = Depends(member_uid)): + _map_errors(presets.delete_preset, org_id, uid, preset_id) + return {"deleted": preset_id} + + +# --- Overview (the dashboard's numbers) ------------------------------------------ + +@app.get("/orgs/{org_id}/overview") +def get_overview(org_id: str, uid: str = Depends(member_uid)): + return _map_errors(overview.get_overview, org_id, uid) + + +# --- Collect (sign-up forms for a list; the public side is backend/collect_api.py) ------ + +class CollectKeyBody(BaseModel): + name: str + database_id: str + allowed_origins: list[str] = [] + fields: list[str] | None = None + double_opt_in: bool = True + mailbox_connection_id: str | None = None + daily_cap: int = 500 + welcome: dict | None = None + + +@app.get("/orgs/{org_id}/collect-keys") +def list_collect_keys(org_id: str, uid: str = Depends(member_uid)): + return _map_errors(collect.list_keys, org_id, uid) + + +@app.post("/orgs/{org_id}/collect-keys") +def create_collect_key(org_id: str, body: CollectKeyBody, uid: str = Depends(member_uid)): + return _map_errors( + collect.create_key, org_id, uid, body.name, body.database_id, body.allowed_origins, + body.fields, body.double_opt_in, body.mailbox_connection_id, body.daily_cap, body.welcome, + ) + + +class WelcomeBody(BaseModel): + welcome: dict | None = None + + +@app.put("/orgs/{org_id}/collect-keys/{key_id}/welcome") +def set_collect_welcome(org_id: str, key_id: str, body: WelcomeBody, uid: str = Depends(member_uid)): + return {"welcome": _map_errors(collect.set_welcome, org_id, uid, key_id, body.welcome)} + + +@app.delete("/orgs/{org_id}/collect-keys/{key_id}") +def revoke_collect_key(org_id: str, key_id: str, uid: str = Depends(member_uid)): + _map_errors(collect.revoke_key, org_id, uid, key_id) + return {"revoked": key_id} + + +# --- Team: members, roles and invites ------------------------------------------ + +@app.get("/orgs/{org_id}/team") +def get_team(org_id: str, uid: str = Depends(org_only_uid)): + role = orgs.get_role(org_id, uid) + can_manage = "manage_team" in orgs.effective_permissions(org_id, uid) + members = [] + for member_uid_, data in orgs.list_members(org_id).items(): + known = {} if data.get("email") else lookup_user(member_uid_) + members.append({ + "uid": member_uid_, "role": data["role"], "extra_roles": data.get("extra_roles", []), "added_at": data.get("added_at"), + "email": data.get("email") or known.get("email", ""), "name": known.get("name", ""), + "you": member_uid_ == uid, + }) + return { + "role": role, + "can_manage": can_manage, + "permissions": PERMISSIONS, + "roles": orgs.list_roles(org_id), + "members": members, + "invites": invites.list_invites(org_id, uid) if can_manage else [], + } + + +class InviteBody(BaseModel): + email: str + role: str + link_base: str + inviter: str = "" + + +def _public_app_base(requested: str) -> str: + """The address invitees open. A link made while testing on a developer's own machine + must never reach a real inbox, so a localhost address becomes the public app.""" + base = requested.strip().rstrip("/") + if os.getenv("LOCAL_MODE", "").lower() in ("1", "true", "yes"): + return base + host = base.split("://", 1)[-1].split("/", 1)[0].split(":", 1)[0].lower() + if host in ("localhost", "127.0.0.1", "[::1]", "") or host.endswith(".localhost"): + return os.getenv("PUBLIC_APP_URL", "https://m8ion.web.app").rstrip("/") + return base + + +@app.post("/orgs/{org_id}/invites") +def create_invite(org_id: str, body: InviteBody, uid: str = Depends(org_only_uid)): + invite = _map_errors(invites.create_invite, org_id, uid, body.email, body.role) + link = f"{_public_app_base(body.link_base)}/invite/{invite['token']}" + emailed = invites.send_invite_email(org_id, invite, link, body.inviter) + return {**invite, "link": link, "emailed": emailed} + + +@app.delete("/orgs/{org_id}/invites/{token}") +def revoke_invite(org_id: str, token: str, uid: str = Depends(org_only_uid)): + _map_errors(invites.revoke_invite, org_id, uid, token) + return {"ok": True} + + +class MemberRoleBody(BaseModel): + role: str + extra_roles: list[str] | None = None + + +@app.put("/orgs/{org_id}/members/{target_uid}") +def change_member_role(org_id: str, target_uid: str, body: MemberRoleBody, uid: str = Depends(org_only_uid)): + _map_errors(orgs.change_member_role, org_id, uid, target_uid, body.role) + if body.extra_roles is not None: + _map_errors(orgs.set_extra_roles, org_id, uid, target_uid, body.extra_roles) + return {"ok": True} + + +@app.get("/orgs/{org_id}/spaces") +def org_spaces(org_id: str, uid: str = Depends(org_only_uid)): + """Every area of the organisation with whether this member may open it.""" + return orgs.spaces_for(org_id, uid) + + +@app.delete("/orgs/{org_id}/members/{target_uid}") +def remove_member(org_id: str, target_uid: str, uid: str = Depends(org_only_uid)): + _map_errors(orgs.remove_member, org_id, uid, target_uid) + return {"ok": True} + + +class RoleBody(BaseModel): + name: str = "" + permissions: list[str] + + +@app.post("/orgs/{org_id}/roles") +def create_role(org_id: str, body: RoleBody, uid: str = Depends(org_only_uid)): + return {"key": _map_errors(orgs.save_role, org_id, uid, None, body.name, body.permissions)} + + +@app.put("/orgs/{org_id}/roles/{key}") +def update_role(org_id: str, key: str, body: RoleBody, uid: str = Depends(org_only_uid)): + return {"key": _map_errors(orgs.save_role, org_id, uid, key, body.name, body.permissions)} + + +@app.delete("/orgs/{org_id}/roles/{key}") +def delete_role(org_id: str, key: str, uid: str = Depends(org_only_uid)): + _map_errors(orgs.delete_role, org_id, uid, key) + return {"ok": True} + + +@app.get("/invites/{token}") +def describe_invite(token: str, uid: str = Depends(current_uid)): + return _map_errors(invites.describe, token) + + +@app.post("/invites/{token}/accept") +def accept_invite(token: str, uid: str = Depends(current_uid), email: str = Depends(current_email)): + _map_errors(accounts.can_join_org, uid) + return {"org_id": _map_errors(invites.accept, token, uid, email)} + + +@app.post("/orgs/{org_id}/leave") +def leave_org(org_id: str, uid: str = Depends(org_only_uid)): + _map_errors(orgs.leave, org_id, uid) + return {"ok": True} + + +# --- Brands -------------------------------------------------------------------- + +@app.get("/orgs/{org_id}/brands") +def list_brands(org_id: str, uid: str = Depends(org_only_uid)): + return brands.list_brands(org_id) + + +@app.post("/orgs/{org_id}/brands") +def create_brand(org_id: str, body: dict, uid: str = Depends(org_only_uid)): + brand_id = _map_errors(brands.create_brand, org_id, uid, body) + return {"brand_id": brand_id, **brands.get_brand(org_id, brand_id)} + + +@app.put("/orgs/{org_id}/brands/{brand_id}") +def update_brand(org_id: str, brand_id: str, body: dict, uid: str = Depends(org_only_uid)): + return _map_errors(brands.update_brand, org_id, uid, brand_id, body) + + +@app.delete("/orgs/{org_id}/brands/{brand_id}") +def delete_brand(org_id: str, brand_id: str, uid: str = Depends(org_only_uid)): + _map_errors(brands.delete_brand, org_id, uid, brand_id) + return {"ok": True} + + +# --- Domain records -------------------------------------------------------------- + +@app.get("/orgs/{org_id}/dns/{domain}") +def check_dns(org_id: str, domain: str, uid: str = Depends(org_only_uid)): + return _map_errors(dns_check.check_domain, domain) + + + +# --- M8ion staff (/system) ----------------------------------------------------------------------- + +def _staff(area: str, *others: str): + """A dependency: the signed-in, verified staff member's email, who must hold one of these roles.""" + def dep(uid: str = Depends(current_uid), email: str = Depends(current_email)) -> str: + roles = staff.roles_of(email) + if not any(staff.can_open(roles, a) for a in (area, *others)): + raise HTTPException(status_code=403, detail="You do not have access to this area") + return email + return dep + + +def _staff_errors(fn, *args, **kwargs): + try: + return fn(*args, **kwargs) + except staff.StaffError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + except verification.VerificationError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + + +@app.get("/staff/me") +def staff_me(uid: str = Depends(current_uid), email: str = Depends(current_email)): + """Every staff area, each marked allowed or not for this person. Anyone may ask.""" + return staff.describe(email) + + +class StaffRolesBody(BaseModel): + email: str + roles: list[str] + + +@app.get("/staff/team") +def staff_team(email: str = Depends(_staff("director"))): + return staff.list_staff() + + +@app.put("/staff/team") +def staff_set_roles(body: StaffRolesBody, email: str = Depends(_staff("director"))): + return _staff_errors(staff.set_roles, email, body.email, body.roles) + + +@app.get("/staff/orgs") +def staff_orgs(email: str = Depends(_staff("admin", "support", "finance"))): + return staff.list_orgs() + + +class StaffOrgBody(BaseModel): + plan: str | None = None + mail_limit: int | None = None + + +@app.put("/staff/orgs/{org_id}") +def staff_update_org(org_id: str, body: StaffOrgBody, email: str = Depends(_staff("admin"))): + return _staff_errors(staff.update_org, email, org_id, body.plan, body.mail_limit, "mail_limit" in body.model_fields_set) + + +@app.get("/staff/verification") +def staff_verification(email: str = Depends(_staff("verification"))): + return verification.queue() + + +class ReviewBody(BaseModel): + decision: str + reason: str = "" + + +@app.put("/staff/verification/{target_uid}/{field}") +def staff_review(target_uid: str, field: str, body: ReviewBody, email: str = Depends(_staff("verification"))): + return _staff_errors(verification.review, email, target_uid, field, body.decision, body.reason) + + +@app.get("/staff/audit") +def staff_audit(email: str = Depends(_staff("compliance", "admin"))): + return staff.recent_audit() diff --git a/backend/auth.py b/backend/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..a62e116521148caf7a432be1e3139bd7708a5d1e --- /dev/null +++ b/backend/auth.py @@ -0,0 +1,85 @@ +""" +Real Firebase ID token verification โ decoupled from LOCAL_MODE (which only governs +storage) and from REAL_SEND_ENABLED (mail transport), same independent-flag pattern as +backend/mailer_client.py. A request either carries a real Firebase ID token +(REAL_AUTH_ENABLED=true) or, for local/dev/test convenience, an X-Dev-Uid header +(REAL_AUTH_ENABLED=false โ the default in tests, see tests/conftest.py). +""" + +from __future__ import annotations + +import os + +import firebase_admin +from fastapi import Header, HTTPException +from firebase_admin import auth as firebase_auth + +from backend.firebase_app import get_app + + +def real_auth_enabled() -> bool: + return os.getenv("REAL_AUTH_ENABLED", "false").lower() == "true" + + +class AuthError(Exception): + pass + + +def verify_id_token(token: str) -> dict: + get_app() + try: + return firebase_auth.verify_id_token(token) + except firebase_admin.exceptions.FirebaseError as exc: + raise AuthError(str(exc)) from exc + + +def current_uid( + authorization: str | None = Header(default=None), + x_dev_uid: str = Header(default="dev-user-1", alias="X-Dev-Uid"), +) -> str: + """FastAPI dependency โ every route that needs "who is calling" uses this instead of + reading X-Dev-Uid directly, so the real/local branch lives in exactly one place.""" + if not real_auth_enabled(): + return x_dev_uid + + if not authorization or not authorization.startswith("Bearer "): + raise HTTPException(status_code=401, detail="Missing bearer token") + + token = authorization[len("Bearer "):] + try: + claims = verify_id_token(token) + except AuthError as exc: + raise HTTPException(status_code=401, detail=f"Invalid token: {exc}") from exc + # Password sign-ups must prove they own the address before touching anything real. + if not claims.get("email_verified", False): + raise HTTPException(status_code=403, detail="Email not verified") + return claims["uid"] + + +def current_email( + authorization: str | None = Header(default=None), + x_dev_email: str = Header(default="", alias="X-Dev-Email"), +) -> str: + """The signed-in address (checked to be verified by current_uid). Used where an + action depends on who the person is, such as accepting an invite.""" + if not real_auth_enabled(): + return x_dev_email + if not authorization or not authorization.startswith("Bearer "): + raise HTTPException(status_code=401, detail="Missing bearer token") + try: + claims = verify_id_token(authorization[len("Bearer "):]) + except AuthError as exc: + raise HTTPException(status_code=401, detail=f"Invalid token: {exc}") from exc + return claims.get("email", "") + + +def lookup_user(uid: str) -> dict: + """{email, name} for a uid, best effort; empty when unknown or running locally.""" + if not real_auth_enabled(): + return {} + try: + get_app() + record = firebase_auth.get_user(uid) + except Exception: # noqa: BLE001 โ a missing name must not break the team list + return {} + return {"email": record.email or "", "name": record.display_name or ""} diff --git a/backend/automations.py b/backend/automations.py new file mode 100644 index 0000000000000000000000000000000000000000..2d1516d1f6b2d79263afb56bf3290a34bf9b2312 --- /dev/null +++ b/backend/automations.py @@ -0,0 +1,304 @@ +"""Sequences, recurring sends and date-based sends. + +An automation is a saved rule that makes ordinary campaigns when its time comes. Each campaign it +makes goes through `sending.queue_campaign`, so the sending window, daily limits, unsubscribe and +suppression, pause and cancel all apply exactly as they do to a campaign sent by hand. + + orgs/{org}/automations/{id} the rule and its progress + active_automations/{org}_{id} the index the timer reads + +Kinds + sequence a list of steps; each person gets step 1, then step 2 `delay_days` after, and so on. + People added to the list later join automatically. + recurring one message to the whole list every N days, weeks or months until it ends. + date one message sent to each person on a date taken from a column (a birthday, an expiry, + an event), a number of days before or after it, optionally every year. +""" + +from __future__ import annotations + +import calendar +import uuid +from datetime import date, datetime, timedelta, timezone + +from backend import databases, mailboxes, orgs, sending +from backend import firestore_client as db + +KINDS = ("sequence", "recurring", "date") +UNITS = ("day", "week", "month") +MAX_STEPS = 10 +MAX_DELAY_DAYS = 365 + + +class AutomationError(ValueError): + """Raised for an invalid automation.""" + + +def _path(org_id: str, automation_id: str) -> str: + return f"orgs/{org_id}/automations/{automation_id}" + + +def _index(org_id: str, automation_id: str) -> str: + return f"active_automations/{org_id}_{automation_id}" + + +def _now() -> datetime: + return datetime.now(timezone.utc) + + +def _parse(value: str, field: str) -> datetime: + try: + when = datetime.fromisoformat(str(value).replace("Z", "+00:00")) + except ValueError: + raise AutomationError(f"{field} is not a date and time") from None + return when if when.tzinfo else when.replace(tzinfo=timezone.utc) + + +def _add_months(day: date, months: int) -> date: + index = day.month - 1 + months + year, month = day.year + index // 12, index % 12 + 1 + return date(year, month, min(day.day, calendar.monthrange(year, month)[1])) + + +def next_after(when: datetime, every: dict) -> datetime: + n, unit = every["interval"], every["unit"] + if unit == "day": + return when + timedelta(days=n) + if unit == "week": + return when + timedelta(weeks=n) + return datetime.combine(_add_months(when.date(), n), when.timetz()) + + +def _clean_steps(steps: list[dict] | None) -> list[dict]: + if not steps or len(steps) > MAX_STEPS: + raise AutomationError(f"A sequence has 1 to {MAX_STEPS} steps") + out = [] + for i, step in enumerate(steps): + subject, body = str(step.get("subject") or "").strip(), str(step.get("html_body") or "") + delay = step.get("delay_days", 0) + if not subject or not body.strip(): + raise AutomationError(f"Step {i + 1} needs a subject and a message") + if not isinstance(delay, int) or not 0 <= delay <= MAX_DELAY_DAYS: + raise AutomationError(f"Step {i + 1}: wait between 0 and {MAX_DELAY_DAYS} days") + out.append({"subject": subject, "html_body": body, "delay_days": delay}) + return out + + +def create(org_id: str, actor_uid: str, spec: dict) -> dict: + orgs.require_permission(org_id, actor_uid, "send") + kind = spec.get("kind") + if kind not in KINDS: + raise AutomationError("Choose sequence, recurring or date") + name = str(spec.get("name") or "").strip() + if not name: + raise AutomationError("Give it a name") + mailboxes.get_mailbox(org_id, spec["mailbox_connection_id"]) + database = databases.get_database(org_id, spec["database_id"]) + + doc = { + "kind": kind, "name": name[:120], "status": "active", "note": "", + "mailbox_connection_id": spec["mailbox_connection_id"], "database_id": spec["database_id"], + "email_column": spec.get("email_column"), "segment": spec.get("segment") or [], + "created_by": actor_uid, "created_at": _now().isoformat(), "runs": 0, + } + start = _parse(spec["start_at"], "Start") if spec.get("start_at") else _now() + if kind == "sequence": + doc |= {"steps": _clean_steps(spec.get("steps")), "start_at": start.isoformat(), "enrolled": {}} + else: + subject, body = str(spec.get("subject") or "").strip(), str(spec.get("html_body") or "") + if not subject or not body.strip(): + raise AutomationError("It needs a subject and a message") + doc |= {"subject": subject, "html_body": body} + if kind == "recurring": + every = spec.get("every") or {} + if every.get("unit") not in UNITS or not isinstance(every.get("interval"), int) or not 1 <= every["interval"] <= 365: + raise AutomationError("Choose how often: every N days, weeks or months") + end = _parse(spec["end_at"], "End").isoformat() if spec.get("end_at") else None + doc |= {"every": {"unit": every["unit"], "interval": every["interval"]}, "next_at": start.isoformat(), "end_at": end} + else: + column = spec.get("date_column") + if column not in [c["name"] for c in database["columns"]]: + raise AutomationError("Choose the column that holds the date") + offset = spec.get("offset_days", 0) + if not isinstance(offset, int) or abs(offset) > MAX_DELAY_DAYS: + raise AutomationError(f"Offset must be within {MAX_DELAY_DAYS} days") + doc |= {"date_column": column, "offset_days": offset, "yearly": bool(spec.get("yearly")), "fired": {}} + + automation_id = uuid.uuid4().hex + db.set_doc(_path(org_id, automation_id), doc) + db.set_doc(_index(org_id, automation_id), {"org_id": org_id, "automation_id": automation_id}) + return get(org_id, actor_uid, automation_id) + + +def get(org_id: str, actor_uid: str, automation_id: str) -> dict: + orgs.require_permission(org_id, actor_uid, "send") + doc = db.get_doc(_path(org_id, automation_id)) + if not doc: + raise orgs.NotFoundError(f"Automation {automation_id!r} not found") + return _public(automation_id, doc) + + +def _public(automation_id: str, doc: dict) -> dict: + out = {k: v for k, v in doc.items() if k not in ("enrolled", "fired")} + out["automation_id"] = automation_id + if doc["kind"] == "sequence": + steps = len(doc["steps"]) + out["people"] = len(doc.get("enrolled", {})) + out["finished"] = sum(1 for e in doc.get("enrolled", {}).values() if e["step"] >= steps) + return out + + +def list_for(org_id: str, actor_uid: str) -> list[dict]: + orgs.require_permission(org_id, actor_uid, "send") + docs = db.query_prefix(f"orgs/{org_id}/automations/") + rows = [_public(path.rsplit("/", 1)[-1], d) for path, d in docs.items()] + return sorted(rows, key=lambda a: a["created_at"], reverse=True) + + +def control(org_id: str, actor_uid: str, automation_id: str, action: str) -> dict: + orgs.require_permission(org_id, actor_uid, "send") + doc = db.get_doc(_path(org_id, automation_id)) + if not doc: + raise orgs.NotFoundError(f"Automation {automation_id!r} not found") + status = doc["status"] + if action == "pause" and status == "active": + new = "paused" + elif action == "resume" and status == "paused": + new = "active" + elif action == "stop" and status in ("active", "paused"): + new = "stopped" + else: + raise AutomationError(f"This is {status}, so it cannot be {action}d") + db.update_doc(_path(org_id, automation_id), {"status": new, "note": ""}) + if new == "active": + db.set_doc(_index(org_id, automation_id), {"org_id": org_id, "automation_id": automation_id}) + else: + db.delete_doc(_index(org_id, automation_id)) + return get(org_id, actor_uid, automation_id) + + +def delete(org_id: str, actor_uid: str, automation_id: str) -> None: + orgs.require_permission(org_id, actor_uid, "send") + db.delete_doc(_path(org_id, automation_id)) + db.delete_doc(_index(org_id, automation_id)) + + +# --- The timer --------------------------------------------------------------- + +def _queue(org_id: str, doc: dict, subject: str, html_body: str, row_ids: list[str]) -> None: + sending.queue_campaign( + org_id, doc["created_by"], subject, html_body, doc["mailbox_connection_id"], doc["database_id"], + doc.get("segment"), email_column=doc.get("email_column"), only_row_ids=row_ids, automated=True, + ) + + +def _rows(org_id: str, doc: dict) -> list[dict]: + database = databases.get_database(org_id, doc["database_id"]) + return sending._recipient_rows(org_id, doc["database_id"], database, doc.get("segment"), doc.get("email_column")) + + +def _row_date(value) -> date | None: + text = str(value or "").strip() + for fmt, size in (("%Y-%m-%d", 10), ("%d/%m/%Y", 10)): + try: + return datetime.strptime(text[:size], fmt).date() + except ValueError: + continue + return None + + +def _step_sequence(org_id: str, doc: dict, now: datetime) -> bool: + if _parse(doc["start_at"], "Start") > now: + return False + enrolled = doc["enrolled"] + rows = _rows(org_id, doc) + for row in rows: # anyone new on the list joins at step one + enrolled.setdefault(row["row_id"], {"step": 0, "next_at": (now + timedelta(days=doc["steps"][0]["delay_days"])).isoformat()}) + live = {r["row_id"] for r in rows} + due: dict[int, list[str]] = {} + for row_id, state in enrolled.items(): + if row_id in live and state["step"] < len(doc["steps"]) and _parse(state["next_at"], "") <= now: + due.setdefault(state["step"], []).append(row_id) + for step_no, row_ids in sorted(due.items()): + step = doc["steps"][step_no] + _queue(org_id, doc, step["subject"], step["html_body"], row_ids) + following = doc["steps"][step_no + 1]["delay_days"] if step_no + 1 < len(doc["steps"]) else 0 + for row_id in row_ids: + enrolled[row_id] = {"step": step_no + 1, "next_at": (now + timedelta(days=following)).isoformat()} + doc["runs"] += 1 + return True # enrolling new people changes the record even when nothing is due + + +def _step_recurring(org_id: str, doc: dict, now: datetime) -> bool: + if _parse(doc["next_at"], "") > now: + return False + end = _parse(doc["end_at"], "") if doc.get("end_at") else None + if end and now > end: + doc["status"] = "done" + return True + _queue(org_id, doc, doc["subject"], doc["html_body"], [r["row_id"] for r in _rows(org_id, doc)]) + doc["runs"] += 1 + nxt = next_after(_parse(doc["next_at"], ""), doc["every"]) + while nxt <= now: # missed periods are skipped, not sent in a burst + nxt = next_after(nxt, doc["every"]) + doc["next_at"] = nxt.isoformat() + return True + + +def _step_date(org_id: str, doc: dict, now: datetime) -> bool: + today = now.date() + due = [] + for row in _rows(org_id, doc): + day = _row_date(row.get(doc["date_column"])) + if day is None: + continue + if doc["yearly"]: + try: + day = day.replace(year=today.year) + except ValueError: # 29 February in a year without one + day = date(today.year, 3, 1) + target = day + timedelta(days=doc["offset_days"]) + key = str(target.year if doc["yearly"] else target) + if target == today and doc["fired"].get(row["row_id"]) != key: + due.append((row["row_id"], key)) + if not due: + return False + _queue(org_id, doc, doc["subject"], doc["html_body"], [r for r, _ in due]) + for row_id, key in due: + doc["fired"][row_id] = key + doc["runs"] += 1 + return True + + +_STEPS = {"sequence": _step_sequence, "recurring": _step_recurring, "date": _step_date} + + +def run_one(org_id: str, automation_id: str, now: datetime | None = None) -> None: + now = now or _now() + doc = db.get_doc(_path(org_id, automation_id)) + if not doc: + raise orgs.NotFoundError(automation_id) + if doc["status"] != "active": + db.delete_doc(_index(org_id, automation_id)) + return + try: + changed = _STEPS[doc["kind"]](org_id, doc, now) + except (ValueError, orgs.NotFoundError) as err: # e.g. the mailbox needs attention: wait for a person + db.update_doc(_path(org_id, automation_id), {"status": "paused", "note": f"Paused: {err}"}) + db.delete_doc(_index(org_id, automation_id)) + return + if changed: + db.set_doc(_path(org_id, automation_id), doc) + if doc["status"] != "active": + db.delete_doc(_index(org_id, automation_id)) + + +def run_due(now: datetime | None = None) -> dict: + checked = 0 + for entry in list(db.query_prefix("active_automations/").values()): + try: + run_one(entry["org_id"], entry["automation_id"], now) + except orgs.NotFoundError: + db.delete_doc(_index(entry["org_id"], entry["automation_id"])) + checked += 1 + return {"checked": checked} diff --git a/backend/brands.py b/backend/brands.py new file mode 100644 index 0000000000000000000000000000000000000000..c35fb0722473af305bb3a4c56178e91412bfc3ad --- /dev/null +++ b/backend/brands.py @@ -0,0 +1,117 @@ +""" +Brands: the businesses one organisation sends for. Each has its own name, logo, domain, +sender name and replies address, and owns some of the org's mailboxes. Lists, saved +emails and the team stay shared across brands. + +A mailbox belongs to at most one brand. When a campaign goes out, the brand that owns +the chosen mailbox supplies the sender details the mailbox doesn't set itself (mailbox, +then brand, then organisation defaults). + +Firestore layout: + orgs/{org_id}/brands/{brand_id} โ {name, logo_url, domain, from_name, reply_to, mailbox_ids, created_at} +""" + +from __future__ import annotations + +import re +import uuid +from datetime import datetime, timezone + +from backend import firestore_client as db +from backend import mailboxes, orgs + +_EMAIL = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$") +_DOMAIN = re.compile(r"^(?=.{3,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$") +FIELDS = ("name", "logo_url", "domain", "from_name", "reply_to", "mailbox_ids") + + +def _path(org_id: str, brand_id: str) -> str: + return f"orgs/{org_id}/brands/{brand_id}" + + +def list_brands(org_id: str) -> list[dict]: + prefix = f"orgs/{org_id}/brands/" + items = [{"brand_id": path[len(prefix):], **data} for path, data in db.query_prefix(prefix).items()] + return sorted(items, key=lambda b: b["name"].lower()) + + +def get_brand(org_id: str, brand_id: str) -> dict: + doc = db.get_doc(_path(org_id, brand_id)) + if doc is None: + raise orgs.NotFoundError(f"No brand {brand_id!r}") + return doc + + +def brand_for_mailbox(org_id: str, connection_id: str) -> dict | None: + return next((b for b in list_brands(org_id) if connection_id in b.get("mailbox_ids", [])), None) + + +def _clean(org_id: str, values: dict, brand_id: str | None) -> dict: + unknown = set(values) - set(FIELDS) + if unknown: + raise ValueError(f"Unknown brand field: {', '.join(sorted(unknown))}") + out = {k: values[k] for k in FIELDS if k in values} + for key in ("name", "from_name"): + if key in out: + out[key] = " ".join(str(out[key] or "").split()).replace('"', "") + if len(out[key]) > 80: + raise ValueError("Keep names to 80 characters or fewer") + if "name" in out: + if not out["name"]: + raise ValueError("Give the brand a name") + if any(b["name"].lower() == out["name"].lower() and b["brand_id"] != brand_id for b in list_brands(org_id)): + raise ValueError(f"There is already a brand called {out['name']!r}") + if "reply_to" in out: + out["reply_to"] = str(out["reply_to"] or "").strip() + if out["reply_to"] and not _EMAIL.match(out["reply_to"]): + raise ValueError("The replies address doesn't look like an email address") + if "domain" in out: + domain = str(out["domain"] or "").strip().lower().removeprefix("https://").removeprefix("http://").removeprefix("www.").rstrip("/") + if domain and not _DOMAIN.match(domain): + raise ValueError("Enter a domain like yourbrand.com") + out["domain"] = domain + if "logo_url" in out: + logo = str(out["logo_url"] or "").strip() + if logo and not logo.startswith("https://"): + raise ValueError("The logo address must start with https://") + out["logo_url"] = logo + if "mailbox_ids" in out: + ids = list(dict.fromkeys(str(i) for i in out["mailbox_ids"] or [])) + for cid in ids: + mailboxes.get_mailbox(org_id, cid) # NotFoundError for anything not in this org + out["mailbox_ids"] = ids + return out + + +def _take_mailboxes(org_id: str, brand_id: str, ids: list[str]) -> None: + """A mailbox moves to this brand: it leaves whichever brand had it.""" + for other in list_brands(org_id): + if other["brand_id"] != brand_id and set(other.get("mailbox_ids", [])) & set(ids): + db.update_doc(_path(org_id, other["brand_id"]), {"mailbox_ids": [i for i in other["mailbox_ids"] if i not in ids]}) + + +def create_brand(org_id: str, actor_uid: str, values: dict) -> str: + orgs.require_permission(org_id, actor_uid, "manage_settings") + clean = _clean(org_id, {"name": values.get("name", "")} | values, None) + brand_id = uuid.uuid4().hex + doc = {"logo_url": "", "domain": "", "from_name": "", "reply_to": "", "mailbox_ids": []} | clean + _take_mailboxes(org_id, brand_id, doc["mailbox_ids"]) + db.set_doc(_path(org_id, brand_id), doc | {"created_at": datetime.now(timezone.utc).isoformat()}) + return brand_id + + +def update_brand(org_id: str, actor_uid: str, brand_id: str, values: dict) -> dict: + orgs.require_permission(org_id, actor_uid, "manage_settings") + get_brand(org_id, brand_id) + clean = _clean(org_id, values, brand_id) + if "mailbox_ids" in clean: + _take_mailboxes(org_id, brand_id, clean["mailbox_ids"]) + db.update_doc(_path(org_id, brand_id), clean) + return {"brand_id": brand_id, **get_brand(org_id, brand_id)} + + +def delete_brand(org_id: str, actor_uid: str, brand_id: str) -> None: + """Its mailboxes stay connected and go back to using the organisation's defaults.""" + orgs.require_permission(org_id, actor_uid, "manage_settings") + get_brand(org_id, brand_id) + db.delete_doc(_path(org_id, brand_id)) diff --git a/backend/certificates.py b/backend/certificates.py new file mode 100644 index 0000000000000000000000000000000000000000..e9eaf6e0870d548af4d4bcadec8205f9d05d5f5b --- /dev/null +++ b/backend/certificates.py @@ -0,0 +1,167 @@ +""" +Per-person certificates: one uploaded image with each recipient's name (or any {Column} text) +drawn onto it, attached to that recipient's copy of a campaign. + +The sender places the text by dragging it on the image in the browser; the position arrives +here as fractions of the image's width and height, so it means the same thing at any display +size. The font size is in the image's own pixels. Fonts are the bundled ones in backend/fonts +(the browser loads the same files) or one the sender uploads for this send. +""" + +from __future__ import annotations + +import base64 +import binascii +import re +from dataclasses import dataclass +from io import BytesIO +from pathlib import Path + +from PIL import Image, ImageDraw, ImageFont, UnidentifiedImageError + +from backend import templating +from backend.email_parts import Attachment, safe_filename + +FONTS_DIR = Path(__file__).parent / "fonts" +BUILTIN_FONTS = { + "sans": "DejaVuSans.ttf", + "sans-bold": "DejaVuSans-Bold.ttf", + "serif": "DejaVuSerif.ttf", + "classic": "IMFellEnglishSC-Regular.ttf", +} +MAX_IMAGE_BYTES = 10 * 1024 * 1024 +MAX_FONT_BYTES = 5 * 1024 * 1024 +MAX_SIDE_PX = 8000 +_COLOR_RE = re.compile(r"^#[0-9a-fA-F]{6}$") + + +@dataclass +class CertificateSpec: + image: Image.Image + text: str + filename: str + x: float + y: float + font_size: int + color: tuple[int, int, int] + font_bytes: bytes + letter_spacing: int + output: str # "png" or "pdf" + + +def _b64(value: str | None, what: str) -> bytes: + try: + return base64.b64decode(value or "", validate=True) + except (binascii.Error, ValueError) as exc: + raise ValueError(f"The {what} could not be read") from exc + + +def parse_spec(raw: dict) -> CertificateSpec: + """Validates the request's certificate settings. Raises ValueError with a message the + sender can act on.""" + image_bytes = _b64(raw.get("image_b64"), "certificate image") + if not image_bytes: + raise ValueError("Choose a certificate image") + if len(image_bytes) > MAX_IMAGE_BYTES: + raise ValueError("The certificate image is larger than 10 MB") + try: + image = Image.open(BytesIO(image_bytes)) + image.load() + except (UnidentifiedImageError, OSError) as exc: + raise ValueError("The certificate image must be a PNG or JPEG") from exc + if max(image.size) > MAX_SIDE_PX: + raise ValueError(f"The certificate image is wider or taller than {MAX_SIDE_PX} pixels") + + text = str(raw.get("text") or "").strip() + if not text: + raise ValueError("Say what to write on the certificate, for example {Name}") + if len(text) > 300: + raise ValueError("The certificate text is too long") + + try: + x, y = float(raw.get("x", 0.5)), float(raw.get("y", 0.5)) + font_size = int(raw.get("font_size", 64)) + letter_spacing = int(raw.get("letter_spacing", 0)) + except (TypeError, ValueError) as exc: + raise ValueError("The certificate text position is not valid") from exc + if not (0 <= x <= 1 and 0 <= y <= 1): + raise ValueError("Place the text inside the image") + if not 6 <= font_size <= 1000: + raise ValueError("Pick a text size between 6 and 1000") + letter_spacing = max(-50, min(200, letter_spacing)) + + color = str(raw.get("color") or "#000000") + if not _COLOR_RE.match(color): + raise ValueError("The text colour must look like #1a2b3c") + + font_key = str(raw.get("font") or "sans") + if font_key == "custom": + font_bytes = _b64(raw.get("font_b64"), "font file") + if not font_bytes or len(font_bytes) > MAX_FONT_BYTES: + raise ValueError("Upload a .ttf or .otf font under 5 MB") + elif font_key in BUILTIN_FONTS: + font_bytes = (FONTS_DIR / BUILTIN_FONTS[font_key]).read_bytes() + else: + raise ValueError("Pick one of the listed fonts") + try: + ImageFont.truetype(BytesIO(font_bytes), 12) + except OSError as exc: + raise ValueError("That font file could not be used") from exc + + output = "pdf" if raw.get("output") == "pdf" else "png" + filename = str(raw.get("filename") or "Certificate for {Name}").strip() or "Certificate" + return CertificateSpec( + image=image, text=text, filename=filename, x=x, y=y, font_size=font_size, + color=tuple(int(color[i:i + 2], 16) for i in (1, 3, 5)), font_bytes=font_bytes, + letter_spacing=letter_spacing, output=output, + ) + + +def render(spec: CertificateSpec, text: str) -> bytes: + """Draws `text` centred on (x, y) and returns the finished file's bytes.""" + img = spec.image.convert("RGBA") + draw = ImageDraw.Draw(img) + font = ImageFont.truetype(BytesIO(spec.font_bytes), spec.font_size) + cx, cy = spec.x * img.width, spec.y * img.height + if spec.letter_spacing == 0: + draw.text((cx, cy), text, font=font, fill=spec.color, anchor="mm") + else: + widths = [font.getlength(ch) for ch in text] + total = sum(widths) + spec.letter_spacing * max(0, len(text) - 1) + x = cx - total / 2 + for ch, w in zip(text, widths): + draw.text((x, cy), ch, font=font, fill=spec.color, anchor="lm") + x += w + spec.letter_spacing + + buf = BytesIO() + if spec.output == "pdf": + img.convert("RGB").save(buf, "PDF", resolution=150) + else: + img.save(buf, "PNG", optimize=True) + return buf.getvalue() + + +def text_for(spec: CertificateSpec, row: dict, columns: list[dict] | None) -> str: + return templating.render(spec.text, row, columns, html=False).strip() + + +def attachment_for(spec: CertificateSpec, row: dict, columns: list[dict] | None) -> Attachment: + text = text_for(spec, row, columns) + name = safe_filename(templating.render(spec.filename, row, columns, html=False), "Certificate") + ext = spec.output + return Attachment( + filename=f"{name}.{ext}", + content_type="application/pdf" if ext == "pdf" else "image/png", + data=render(spec, text), + ) + + +def preview_png(spec: CertificateSpec, text: str, max_width: int = 1400) -> bytes: + """A PNG of the certificate for the composer, scaled down so it loads quickly.""" + png_spec = CertificateSpec(**{**spec.__dict__, "output": "png"}) + img = Image.open(BytesIO(render(png_spec, text))) + if img.width > max_width: + img = img.resize((max_width, round(img.height * max_width / img.width)), Image.LANCZOS) + buf = BytesIO() + img.save(buf, "PNG", optimize=True) + return buf.getvalue() diff --git a/backend/collect.py b/backend/collect.py new file mode 100644 index 0000000000000000000000000000000000000000..765e4d802bac89cc2227de3656a46d76e95ffe5e --- /dev/null +++ b/backend/collect.py @@ -0,0 +1,352 @@ +""" +Public collection ("Collect") โ lets people on a user's own website land in one of that user's +databases through a public key + a snippet. See docs/blueprint/adr/0006. + +The public key is NOT a secret and can do almost nothing: create a *pending* sign-up. Its rules +live here, server-side (allowed origins, allowed columns, daily cap, double opt-in). A sign-up +only becomes a database row once the person confirms from their inbox, and every check that +could stop a bot runs BEFORE a confirmation email is sent โ that email goes out from the user's +own mailbox, so one sent to a stranger costs the user's sender reputation. + +This module is the only thing the public router (backend/collect_api.py) may call. It never +reads rows out, never exposes credentials, and never sends a campaign. +""" + +from __future__ import annotations + +import hashlib +import html +import json +import logging +import os +import secrets +import uuid +from datetime import datetime, timedelta, timezone + +from backend import databases, mailboxes, mailer_client, orgs, rate_limiter +from backend import firestore_client as db +from backend.core import constants as C +from backend.crypto_utils import decrypt, encrypt +from backend.mock_mailer import AuthError, ConnectionFailure + + +class CollectError(Exception): + """A hard rejection the public caller is allowed to see. `status` is the HTTP code.""" + + def __init__(self, status: int, message: str): + self.status = status + super().__init__(message) + + +def _now() -> datetime: + return datetime.now(timezone.utc) + + +def _key_path(org_id: str, key_id: str) -> str: + return f"orgs/{org_id}/collect_keys/{key_id}" + + +def _index_path(public_key: str) -> str: + return f"collect_index/{public_key}" + + +def _pending_path(token: str) -> str: + return f"collect_pending/{token}" + + +def _consent_path(org_id: str, row_id: str) -> str: + return f"orgs/{org_id}/consents/{row_id}" + + +def _blocked(field: str) -> bool: + lowered = field.lower() + return any(word in lowered for word in C.COLLECT_BLOCKED_FIELD_WORDS) + + +def _normalize_origin(origin: str) -> str: + origin = origin.strip().rstrip("/").lower() + if not (origin.startswith("http://") or origin.startswith("https://")) or "/" in origin.split("://", 1)[1]: + raise ValueError(f"{origin!r} is not a site address. Use something like https://example.com") + return origin + + +def _email_column(database: dict) -> str | None: + for col in database["columns"]: + if col["type"] == "email": + return col["name"] + return None + + +# --- Key management (signed-in users) --------------------------------------- + +def _clean_welcome(org_id: str, welcome: dict | None, default_mailbox: str | None) -> dict | None: + """A welcome email: {subject, html_body, mailbox_connection_id}, or None for no welcome.""" + if not welcome or not (welcome.get("subject") or welcome.get("html_body")): + return None + subject, body = str(welcome.get("subject", "")).strip(), str(welcome.get("html_body", "")).strip() + if not subject or not body: + raise ValueError("A welcome email needs both a subject and a message") + mailbox_id = welcome.get("mailbox_connection_id") or default_mailbox + if not mailbox_id: + raise ValueError("Pick a mailbox to send the welcome email from") + if mailboxes.get_mailbox(org_id, mailbox_id)["status"] != "verified": + raise ValueError("That mailbox is not verified yet, so it cannot send the welcome email.") + return {"subject": subject, "html_body": body, "mailbox_connection_id": mailbox_id} + + +def set_welcome(org_id: str, actor_uid: str, key_id: str, welcome: dict | None) -> dict | None: + orgs.require_permission(org_id, actor_uid, "edit_lists") + doc = db.get_doc(_key_path(org_id, key_id)) + if doc is None: + raise orgs.NotFoundError(f"No form {key_id!r}") + cleaned = _clean_welcome(org_id, welcome, doc.get("mailbox_connection_id")) + db.update_doc(_key_path(org_id, key_id), {"welcome": cleaned}) + return cleaned + + +def _send_welcome(org_id: str, key: dict, row_id: str) -> None: + """Queues the form's welcome email to the one person who just joined. A failure here never + turns away the sign-up; the person is on the list either way.""" + welcome = key.get("welcome") + if not welcome: + return + from backend import sending # late: sending pulls in much of the app + + try: + sending.queue_campaign( + org_id, key.get("created_by", ""), welcome["subject"], welcome["html_body"], welcome["mailbox_connection_id"], + key["database_id"], only_row_ids=[row_id], automated=True, + ) + except Exception: # noqa: BLE001 - see docstring + logging.getLogger(__name__).exception("Welcome email for form %s could not be queued", key.get("name")) + + +def create_key( + org_id: str, actor_uid: str, name: str, database_id: str, allowed_origins: list[str], + fields: list[str] | None = None, double_opt_in: bool = True, + mailbox_connection_id: str | None = None, daily_cap: int = C.COLLECT_DEFAULT_DAILY_CAP, + welcome: dict | None = None, +) -> dict: + orgs.require_permission(org_id, actor_uid, "edit_lists") + name = name.strip() + if not name or len(name) > 80: + raise ValueError("Give the form a name (up to 80 characters)") + database = databases.get_database(org_id, database_id) + email_column = _email_column(database) + if email_column is None: + raise ValueError("This list has no email column yet, so people cannot sign up to it. Set one first.") + + column_names = [c["name"] for c in database["columns"]] + chosen = column_names if not fields else fields + unknown = [f for f in chosen if f not in column_names] + if unknown: + raise ValueError(f"Not a column in this list: {', '.join(unknown)}") + chosen = [f for f in chosen if not _blocked(f)] + if email_column not in chosen: + chosen.insert(0, email_column) + + if double_opt_in: + if not mailbox_connection_id: + raise ValueError("Pick a mailbox to send the confirmation email from, or turn confirmation off.") + if mailboxes.get_mailbox(org_id, mailbox_connection_id)["status"] != "verified": + raise ValueError("That mailbox is not verified yet, so it cannot send confirmation emails.") + if not 1 <= daily_cap <= 10_000: + raise ValueError("Daily limit must be between 1 and 10,000") + + origins = list(dict.fromkeys(_normalize_origin(o) for o in allowed_origins if o.strip())) + key_id = uuid.uuid4().hex + public_key = "pk_" + secrets.token_urlsafe(18) + doc = { + "name": name, + "database_id": database_id, + "public_key": public_key, + "allowed_origins": origins, + "fields": chosen, + "double_opt_in": double_opt_in, + "mailbox_connection_id": mailbox_connection_id if double_opt_in else None, + "daily_cap": daily_cap, + "welcome": _clean_welcome(org_id, welcome, mailbox_connection_id), + "created_by": actor_uid, + "revoked": False, + "created_at": _now().isoformat(), + } + db.set_doc(_key_path(org_id, key_id), doc) + db.set_doc(_index_path(public_key), {"org_id": org_id, "key_id": key_id}) + return doc | {"key_id": key_id} + + +def list_keys(org_id: str, actor_uid: str) -> list[dict]: + orgs.require_permission(org_id, actor_uid) + prefix = f"orgs/{org_id}/collect_keys/" + items = [data | {"key_id": path[len(prefix):]} for path, data in db.query_prefix(prefix).items()] + return sorted(items, key=lambda k: k["created_at"], reverse=True) + + +def revoke_key(org_id: str, actor_uid: str, key_id: str) -> None: + orgs.require_permission(org_id, actor_uid, "edit_lists") + doc = db.get_doc(_key_path(org_id, key_id)) + if doc is None: + raise orgs.NotFoundError(f"No form {key_id!r}") + db.update_doc(_key_path(org_id, key_id), {"revoked": True}) + db.delete_doc(_index_path(doc["public_key"])) + + +# --- Public side --------------------------------------------------------------- + +def _load_key(public_key: str) -> tuple[str, str, dict]: + index = db.get_doc(_index_path(public_key)) + if index is None: + raise CollectError(404, "Unknown form") + doc = db.get_doc(_key_path(index["org_id"], index["key_id"])) + if doc is None or doc["revoked"]: + raise CollectError(404, "Unknown form") + return index["org_id"], index["key_id"], doc + + +def allowed_origin(public_key: str, origin: str | None) -> str | None: + """The value for Access-Control-Allow-Origin for this key and caller, or None.""" + try: + _, _, key = _load_key(public_key) + except CollectError: + return None + if not origin: + return None + origin = origin.strip().rstrip("/").lower() + if not key["allowed_origins"] or origin in key["allowed_origins"]: + return origin + return None + + +def submit(public_key: str, payload: object, origin: str | None, client_ip: str) -> dict: + """Handles one public sign-up. Returns {"ok": True, "pending": bool}. Raises CollectError + only for things a real visitor or the site owner needs to know about; bots caught by the + cheap checks get a normal-looking success so they learn nothing.""" + org_id, key_id, key = _load_key(public_key) + pending_mode = key["double_opt_in"] + ok = {"ok": True, "pending": pending_mode} + + if key["allowed_origins"] and (not origin or origin.strip().rstrip("/").lower() not in key["allowed_origins"]): + raise CollectError(403, "This form is not allowed on this site") + + if not isinstance(payload, dict) or not isinstance(payload.get("fields"), dict): + raise CollectError(400, "Malformed submission") + raw_fields = payload["fields"] + if len(raw_fields) > C.COLLECT_MAX_FIELDS or len(json.dumps(payload)) > C.COLLECT_MAX_BODY_BYTES: + raise CollectError(413, "Submission is too large") + + # Cheap bot checks: honeypot filled, or filled in faster than a person can. + if payload.get("hp"): + return ok + elapsed = payload.get("t") + if isinstance(elapsed, (int, float)) and elapsed < C.COLLECT_MIN_FILL_SECONDS * 1000: + return ok + + if not rate_limiter.allow_hit(f"collect-key:{key_id}", C.COLLECT_PER_KEY_PER_MINUTE, 60): + raise CollectError(429, "Too many sign-ups right now. Try again in a minute.") + ip_hash = hashlib.sha256(client_ip.encode()).hexdigest()[:16] + if not rate_limiter.allow_hit(f"collect-ip:{ip_hash}", C.COLLECT_PER_IP_PER_MINUTE, 60): + raise CollectError(429, "Too many sign-ups from your connection. Try again in a minute.") + + database = databases.get_database(org_id, key["database_id"]) + email_column = _email_column(database) + if email_column is None: + raise CollectError(409, "This form is not set up correctly") + + values = {} + for name, value in raw_fields.items(): + if name not in key["fields"] or _blocked(name) or isinstance(value, (dict, list)): + continue + text = str(value).strip()[: C.COLLECT_MAX_VALUE_LENGTH] + if text: + values[name] = text + + email = values.get(email_column, "") + if not databases.EMAIL_RE.match(email): + raise CollectError(400, "Please enter a valid email address") + + if not rate_limiter.allow_hit(f"collect-day:{key_id}", key["daily_cap"], 86_400): + raise CollectError(429, "This form has reached its daily limit") + + digest = hashlib.sha256(email.lower().encode()).hexdigest()[:20] + if not rate_limiter.allow_hit(f"collect-addr:{key_id}:{digest}", C.COLLECT_PER_ADDRESS_PER_HOUR, 3600): + return ok # already asked recently; do not email them again, do not say so + + existing = databases.list_rows(org_id, key["database_id"]) + if any(str(r.get(email_column, "")).strip().lower() == email.lower() for r in existing): + return ok # already on the list; do not reveal that + + if not pending_mode: + row_id = databases.insert_row(org_id, key["database_id"], values) + _record_consent(org_id, row_id, key_id, email) + _send_welcome(org_id, key, row_id) + return ok + + token = secrets.token_urlsafe(24) + expires = _now() + timedelta(hours=C.COLLECT_CONFIRM_TTL_HOURS) + db.set_doc(_pending_path(token), { + "org_id": org_id, + "key_id": key_id, + "database_id": key["database_id"], + "encrypted_values": encrypt(json.dumps(values)), + "expires_at": expires.isoformat(), + }) + try: + _send_confirmation(org_id, key, email, token) + except CollectError: + db.delete_doc(_pending_path(token)) + raise + return ok + + +def _send_confirmation(org_id: str, key: dict, email: str, token: str) -> None: + try: + rate_limiter.check_and_consume(org_id, count=1) + except rate_limiter.RateLimitExceeded as exc: + raise CollectError(429, "Confirmation emails are paused for now. Try again later.") from exc + connection = mailboxes.get_mailbox(org_id, key["mailbox_connection_id"]) + if connection["status"] != "verified": + raise CollectError(503, "This form cannot send confirmation emails right now") + org_name = html.escape(orgs.get_org(org_id)["name"]) + base = os.getenv("PUBLIC_API_BASE_URL", "http://localhost:8000").rstrip("/") + link = f"{base}/collect/confirm/{token}" + body = ( + f"
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 + 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..358ae7f0b672c6ea2833d3814bd1e848b1b00dcd --- /dev/null +++ b/backend/overview.py @@ -0,0 +1,68 @@ +""" +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 collect, databases, mailboxes, orgs, presets, sending + +_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} + return { + "people": sum(d.get("row_count", 0) for d in lists if not d.get("disabled")), + "lists": len(lists), + "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": sorted( + ({"database_id": d["database_id"], "name": d["name"], "row_count": d.get("row_count", 0)} for d in lists), + key=lambda d: d["row_count"], reverse=True, + )[:5], + } 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..ae304a8dc07929c40a79a8f901056417fb775346 --- /dev/null +++ b/backend/sending.py @@ -0,0 +1,656 @@ +""" +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 time +import uuid +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 +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 = databases.get_database(org_id, database_id) + columns = database["columns"] + problems = _template_problems(subject, html_body, columns) + rows = databases.list_rows(org_id, database_id) + if segment: + rows = databases.apply_segment(rows, columns, segment) + email_column = _email_column(database, email_column) + if email_column: + rows = [r for r in rows if r.get(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]: + rows = databases.list_rows(org_id, database_id) + if segment: + rows = databases.apply_segment(rows, database["columns"], segment) + email_column = _email_column(database, email_column) + return [r for r in rows if email_column and r.get(email_column)] + + +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 = 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] = {} + + +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 = 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: + return _process(org_id, send_id, now or datetime.now(timezone.utc), budget_seconds) + 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 = 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) + + 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 ""), + attachments=files, inline_images=inline_images, headers=unsubscribe.headers(org_id, address, send.get("from_email") or ""), + ) + # "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 + 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")), + }) + 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_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..9cba3ff6d5e44c78abe2f2b2cf6664581262e791 --- /dev/null +++ b/backend/unsubscribe.py @@ -0,0 +1,154 @@ +""" +Opting out of email. Every campaign email carries a signed link (and the one-click header mail +apps look for) that adds the address to the organisation's suppression list; sends skip anyone on +it. The link holds the organisation and address, signed so it cannot be forged or edited, and +needs no sign-in. Members can also see the list, add an address by hand and take one off. + + orgs/{org_id}/suppressions/{key} โ {email, reason, 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) -> str: + return hashlib.sha256(email.strip().lower().encode()).hexdigest()[:32] + + +def _path(org_id: str, email: str) -> str: + return f"orgs/{org_id}/suppressions/{_key(email)}" + + +def _sign(payload: str) -> str: + return hmac.new(_secret(), payload.encode(), hashlib.sha256).hexdigest()[:32] + + +def make_token(org_id: str, email: str) -> str: + payload = base64.urlsafe_b64encode(f"{org_id}|{email.strip().lower()}".encode()).decode().rstrip("=") + return f"{payload}.{_sign(payload)}" + + +def parse_token(token: str) -> tuple[str, str]: + """(org_id, email) for a genuine token; ValueError for anything else.""" + payload, _, signature = token.partition(".") + if not payload or not hmac.compare_digest(signature, _sign(payload)): + raise ValueError("This unsubscribe link is not valid") + try: + org_id, _, email = base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)).decode().partition("|") + except Exception as exc: # undecodable payload + raise ValueError("This unsubscribe link is not valid") from exc + if not org_id or not _EMAIL_RE.match(email): + raise ValueError("This unsubscribe link is not valid") + return org_id, email + + +def link(org_id: str, email: str, sender: 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)}" + return f"mailto:{sender}?subject=Unsubscribe" if sender else "" + + +def headers(org_id: str, email: str, sender: 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) + 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 = "") -> 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) + return ( + '
{html.escape(str(exc))}.
"), status_code=400) + return unsubscribe.page( + "Unsubscribe", + f"Stop emails to {html.escape(email)}?
" + f'', + ) + + +@router.post("/u/{token}", response_class=HTMLResponse) +def unsubscribe_now(token: str): + try: + email = unsubscribe.unsubscribe_with_token(token) + except ValueError as exc: + return HTMLResponse(unsubscribe.page("Link not valid", f"{html.escape(str(exc))}.
"), status_code=400) + return unsubscribe.page("You are unsubscribed", f"{html.escape(email)} will not get more emails from this sender.
") 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/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..f52a9b52ba429bfc35d3de85e36190d024572a54 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,13 @@ +# 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