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'

Yes, add me

' + 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 = """ +{title} + +

{title}

{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/). Everyone in the org sees every area listed; an +# area opens only for a member whose role (or extra roles) carries it. More will be added. +SPACES: dict[str, tuple[str, str]] = { + "admin": ("Admin", "Team, mailboxes and organisation settings."), + "director": ("Director", "How the whole organisation is doing."), + "accountant": ("Accountant", "Receipts and money matters."), + "marketer": ("Marketer", "Campaigns, audiences and presets."), + "auditor": ("Auditor", "A read-only look at what was done and by whom."), +} + +# Which areas each role opens. Owner opens all. Admin opens all except accountant and director. +ROLE_SPACES: dict[str, list[str]] = { + "owner": list(SPACES), + "admin": ["admin", "marketer", "auditor"], + "director": ["director"], + "accountant": ["accountant"], + "marketer": ["marketer"], + "editor": ["marketer"], + "auditor": ["auditor"], +} + +# Older stored role names, read as their current equivalent. +ROLE_ALIASES: dict[str, str] = {"operator": "editor"} + +# Days an invite link stays usable. +INVITE_TTL_DAYS = 7 + +# The role assigned automatically to whoever creates an org. Not assignable via +# add_member โ€” ownership only exists by creating the org (transfer is out of scope for now). +ORG_CREATOR_ROLE = "owner" + +# --------------------------------------------------------------------------- +# Mailbox connections โ€” see docs/blueprint/adr/0001-relay-not-esp.md +# --------------------------------------------------------------------------- + +# Providers that get the OAuth path. Everything else falls through to raw SMTP credentials. +SUPPORTED_OAUTH_PROVIDERS: tuple[str, ...] = ("gmail", "outlook", "yahoo") + +# Days between changes to a connected mailbox's sign-in details (a change re-runs the test). +MAILBOX_CREDENTIAL_CHANGE_DAYS = 30 + +# Highest daily send limit an org can set on one mailbox. 0 means no limit of our own. +MAILBOX_DAILY_LIMIT_MAX = 10_000 + +# Number of OTP verification messages sent in the mailbox-connection round-trip +# (docs/product/srs.md FR-6). +VERIFICATION_OTP_COUNT = 3 + +# Seconds to wait for all VERIFICATION_OTP_COUNT messages to arrive before treating the +# connection as a silent failure (SRS FR-7). Prototype placeholder. +VERIFICATION_TIMEOUT_SECONDS = 300 + +# --------------------------------------------------------------------------- +# Rate limiting & abuse prevention โ€” see docs/blueprint/blueprint.md "Rate limiting" +# --------------------------------------------------------------------------- + +# Default hourly send cap per account, enforced server-side via a rolling token bucket. +# Prototype placeholder โ€” real tiering happens in PLAN_TIERS below once pricing is set. +DEFAULT_HOURLY_SEND_CAP = 100 + +# Escalation stages for anomaly detection, in order. Each stage's threshold is a multiple +# of the account's own rolling baseline rate, not an absolute number. +RATE_ANOMALY_ESCALATION_STAGES: tuple[str, ...] = ( + "detect", + "block", + "silently_report", + "auto_temporary_ban", +) + +# --------------------------------------------------------------------------- +# Bounce handling โ€” see docs/blueprint/blueprint.md "Sending pipeline" +# --------------------------------------------------------------------------- + +# Soft-bounce retry ceiling before escalating to a person. Prototype placeholder. +SOFT_BOUNCE_RETRY_CEILING = 5 + +# Backoff schedule (seconds) between soft-bounce retries, up to the ceiling above. +SOFT_BOUNCE_BACKOFF_SECONDS: tuple[int, ...] = (60, 300, 900, 3600, 14400) + +# Initial window (seconds) to match an inbound message to a specific sent OTP/message by +# direct reference before escalating to the broader regex rescan pass. +BOUNCE_MATCH_INITIAL_WINDOW_SECONDS = 120 + +# --------------------------------------------------------------------------- +# Billing โ€” see docs/blueprint/adr/0005-per-recipient-pay-as-you-go-billing.md +# --------------------------------------------------------------------------- + +# Soft-cap usage warning thresholds, as a fraction of an org's monthly free allowance. +# Fires on all 3 surfaces (email, in-app, control panel banner) per SRS FR-28. +SOFT_CAP_WARNING_THRESHOLDS: tuple[float, ...] = (0.8, 1.0) + +# Plan tiers. Real pricing/allowances are a business decision (see ADR-0005) โ€” these are +# structural placeholders so the billing code has real shapes to run tests against. +PLAN_TIERS: dict[str, dict[str, object]] = { + "free": { + "monthly_recipient_allowance": 500, # prototype placeholder + "hourly_send_cap": DEFAULT_HOURLY_SEND_CAP, + "storage_mb": 250, # prototype placeholder + "overage_allowed": False, + }, + "paid": { + "monthly_recipient_allowance": None, # unlimited within pay-as-you-go + "hourly_send_cap": DEFAULT_HOURLY_SEND_CAP * 5, # prototype placeholder + "storage_mb": 5000, # prototype placeholder + "overage_allowed": True, + }, +} + +# --------------------------------------------------------------------------- +# M8ion's own outbound identity โ€” see docs/blueprint/blueprint.md "M8ion's own outbound mail" +# --------------------------------------------------------------------------- + +# Prototype-only sending address for M8ion's own transactional mail. Replaced with a real +# registered domain before Phase 3. +SYSTEM_SENDER_ADDRESS_PROTO = "projects.techies.26@gmail.com" + +# The receiving side of the mailbox-verification round-trip (SRS FR-6) โ€” "M8ion's own test +# mailbox". Prototype placeholder; becomes a real address once a domain is registered. +SYSTEM_TEST_MAILBOX_ADDRESS_PROTO = "verify-test@m8ion-test.local" + +# --------------------------------------------------------------------------- +# Public collection endpoint (docs/blueprint/adr/0006) โ€” all prototype placeholders +# --------------------------------------------------------------------------- + +COLLECT_MAX_BODY_BYTES = 8_000 +COLLECT_MAX_FIELDS = 30 +COLLECT_MAX_VALUE_LENGTH = 500 +COLLECT_MIN_FILL_SECONDS = 2 # a human cannot fill a form faster than this +COLLECT_PER_KEY_PER_MINUTE = 30 +COLLECT_PER_IP_PER_MINUTE = 10 +COLLECT_PER_ADDRESS_PER_HOUR = 1 # confirmation emails to one address, per key +COLLECT_DEFAULT_DAILY_CAP = 500 +COLLECT_CONFIRM_TTL_HOURS = 48 +# Field names that are never collected, whatever the key allows. +COLLECT_BLOCKED_FIELD_WORDS = ("password", "passwd", "pwd", "card", "cvv", "cvc", "ssn", "secret", "token") diff --git a/backend/crypto_utils.py b/backend/crypto_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9ebd73887e03501d3dec03adc1293f8f9040a13a --- /dev/null +++ b/backend/crypto_utils.py @@ -0,0 +1,35 @@ +""" +Prototype-only stand-in for ADR-0002's GCP KMS envelope encryption. No GCP project is +provisioned yet (see docs/blueprint/blueprint.md), so mailbox credentials and contact PII +are encrypted at rest here using a single symmetric Fernet key from CREDENTIAL_ENCRYPTION_KEY +(.env) instead of KMS-wrapped per-record data keys. + +This is a real, working encryption layer โ€” not a no-op โ€” but it is NOT the security posture +ADR-0002 commits to for production: one key, no envelope, no separate audit-logged access +control. Every function here is the seam that gets replaced (same call signatures) once a +GCP project with KMS exists. +""" + +from __future__ import annotations + +import os + +from cryptography.fernet import Fernet + +_key = os.getenv("CREDENTIAL_ENCRYPTION_KEY") +if not _key: + # Auto-generated per-process when unset, matching the prior build's local-dev fallback. + # Encrypted values won't survive a process restart with a fresh key โ€” fine for tests + # and throwaway local runs, NOT fine for anything meant to persist. Set + # CREDENTIAL_ENCRYPTION_KEY in .env for a stable local key across restarts. + _key = Fernet.generate_key().decode() + +_fernet = Fernet(_key.encode() if isinstance(_key, str) else _key) + + +def encrypt(plaintext: str) -> str: + return _fernet.encrypt(plaintext.encode()).decode() + + +def decrypt(token: str) -> str: + return _fernet.decrypt(token.encode()).decode() diff --git a/backend/customizations.py b/backend/customizations.py new file mode 100644 index 0000000000000000000000000000000000000000..b92adf429885f1ed13fdc0be769cfd06fd4d005d --- /dev/null +++ b/backend/customizations.py @@ -0,0 +1,91 @@ +""" +Saved email "customizations" โ€” a named header + footer + brand color a company designs once +and picks per campaign, instead of redesigning them on every send. Stored per org at +orgs/{org_id}/customizations/{id}. The frontend merges the chosen customization around the +message body into the final HTML (frontend/src/lib/emailFrame.ts), so sending itself is +unchanged and never needs to know which customization was used. +""" + +from __future__ import annotations + +import re +import uuid +from datetime import datetime, timezone + +from backend import firestore_client as db +from backend import orgs + +_COLOR_RE = re.compile(r"^#[0-9a-fA-F]{6}$") +_MAX_NAME = 80 +_MAX_HTML = 20_000 + + +def _now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def _prefix(org_id: str) -> str: + return f"orgs/{org_id}/customizations/" + + +def _path(org_id: str, customization_id: str) -> str: + return f"{_prefix(org_id)}{customization_id}" + + +def _clean(name: str, brand_color: str, logo_url: str, header_text: str, footer_html: str, footer_bg: str) -> dict: + name = name.strip() + if not name or len(name) > _MAX_NAME: + raise ValueError(f"Name is required and must be at most {_MAX_NAME} characters") + if not _COLOR_RE.match(brand_color): + raise ValueError("Brand color must be a hex color like #c0392b") + if not _COLOR_RE.match(footer_bg): + raise ValueError("Footer background must be a hex color like #f4f4f4") + logo_url = logo_url.strip() + if logo_url and not logo_url.lower().startswith("https://"): + raise ValueError("Logo URL must start with https://") + if len(footer_html) > _MAX_HTML or len(header_text) > 200: + raise ValueError("Header or footer is too long") + return { + "name": name, + "brand_color": brand_color, + "logo_url": logo_url, + "header_text": header_text.strip(), + "footer_html": footer_html, + "footer_bg": footer_bg, + } + + +def create_customization(org_id: str, actor_uid: str, name: str, brand_color: str, logo_url: str, + header_text: str, footer_html: str, footer_bg: str = "#f4f4f4") -> str: + orgs.require_permission(org_id, actor_uid, "edit_emails") + data = _clean(name, brand_color, logo_url, header_text, footer_html, footer_bg) + customization_id = uuid.uuid4().hex + db.set_doc(_path(org_id, customization_id), data | {"created_at": _now(), "updated_at": _now()}) + return customization_id + + +def update_customization(org_id: str, actor_uid: str, customization_id: str, name: str, brand_color: str, + logo_url: str, header_text: str, footer_html: str, footer_bg: str = "#f4f4f4") -> None: + orgs.require_permission(org_id, actor_uid, "edit_emails") + get_customization(org_id, customization_id) + data = _clean(name, brand_color, logo_url, header_text, footer_html, footer_bg) + db.update_doc(_path(org_id, customization_id), data | {"updated_at": _now()}) + + +def delete_customization(org_id: str, actor_uid: str, customization_id: str) -> None: + orgs.require_permission(org_id, actor_uid, "edit_emails") + get_customization(org_id, customization_id) + db.delete_doc(_path(org_id, customization_id)) + + +def get_customization(org_id: str, customization_id: str) -> dict: + doc = db.get_doc(_path(org_id, customization_id)) + if doc is None: + raise orgs.NotFoundError(f"No customization {customization_id!r} in org {org_id!r}") + return doc + + +def list_customizations(org_id: str, actor_uid: str) -> dict[str, dict]: + orgs.require_permission(org_id, actor_uid) + prefix = _prefix(org_id) + return {path[len(prefix):]: data for path, data in db.query_prefix(prefix).items()} diff --git a/backend/databases.py b/backend/databases.py new file mode 100644 index 0000000000000000000000000000000000000000..533bd544d14190ef17c6a5be58f4252a8b45a1bb --- /dev/null +++ b/backend/databases.py @@ -0,0 +1,835 @@ +""" +Audience "databases" โ€” a parsed upload (CSV/XLSX/JSON), cleaned, classified, and normalized +(see backend/normalize.py for exactly what "normalized" means here and why it stops short of +blind full 5NF). Replaces the old flat backend/audiences.py contact list: a row now belongs to +a named, typed database rather than floating in one flat per-org list. + +Column types: email, contact (phone), name, tag, bool, link, text (default). The auto- +classifier runs once at upload time; a column's type can be changed later via +update_column_type, which requires at least one existing value to conform to the new type's +syntax and flags (not blocks) every row that doesn't. + +Encryption follows the same posture as the old contacts module (SRS FR-15): row data and +lookup-table data are both encrypted at rest via backend.crypto_utils, same mechanism as +mailbox credentials. +""" + +from __future__ import annotations + +import csv +import io +import json +import re +import uuid +from datetime import datetime, timezone + +from backend import firestore_client as db +from backend import normalize +from backend.templating import split_items +from backend import orgs +from backend.crypto_utils import decrypt, encrypt + +COLUMN_TYPES: tuple[str, ...] = ("email", "contact", "name", "tag", "bool", "link", "date", "text") + +EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$") +# Sheets exports often prefix phone numbers with a stray apostrophe ('+234...) to stop them +# being read as numbers; tolerate it rather than call the whole column text. +PHONE_RE = re.compile(r"^'?\+?[\d][\d\s\-().]{5,}$") +# Dates and timestamps: 2004-05-17, 2024/03/09 14:22:01 GMT+1, 17/05/2004, 17 May 2004, +# 2025-01-02T10:00:00.000Z. Checked before PHONE_RE, which would otherwise swallow digits-and-dashes. +_TIME = r"\d{1,2}:\d{2}(:\d{2}(\.\d+)?)?(\s*(am|pm))?(\s*(z|gmt|utc|[a-z]{3})?\s*([+-]\d{1,2}(:?\d{2})?)?)?" +DATE_RE = re.compile( + rf"^(\d{{4}}[-/.]\d{{1,2}}[-/.]\d{{1,2}}([ T]{_TIME})?" + rf"|\d{{1,2}}[-/.]\d{{1,2}}[-/.]\d{{2,4}}([ T]{_TIME})?" + r"|\d{1,2}\s+[A-Za-z]{3,9}\.?,?\s+\d{4}" + r"|[A-Za-z]{3,9}\.?\s+\d{1,2},?\s+\d{4})$", + re.IGNORECASE, +) +# "18 - 24", "25-34": a range of small numbers, not a phone number. +RANGE_RE = re.compile(r"^\d{1,3}\s*(-|to|โ€“)\s*\d{1,3}\+?$|^\d{1,3}\+$", re.IGNORECASE) +URL_RE = re.compile(r"^(https?://|www\.)\S+$", re.IGNORECASE) +BOOL_VALUES = {"true", "false", "yes", "no", "y", "n", "1", "0"} + +# None of these three ever raise for an empty cell โ€” an unfilled field isn't a conformance +# failure, only a filled-but-malformed one is. +TYPE_VALIDATORS = { + "email": lambda v: bool(EMAIL_RE.match(v.strip())), + "contact": lambda v: bool(PHONE_RE.match(v.strip())) and not DATE_RE.match(v.strip()), + "date": lambda v: bool(DATE_RE.match(v.strip())), + "link": lambda v: bool(URL_RE.match(v.strip())), + "bool": lambda v: v.strip().lower() in BOOL_VALUES, +} + + +class ValidationError(Exception): + pass + + +def _now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def _database_path(org_id: str, database_id: str) -> str: + return f"orgs/{org_id}/databases/{database_id}" + + +def _row_path(org_id: str, database_id: str, row_id: str) -> str: + return f"orgs/{org_id}/databases/{database_id}/rows/{row_id}" + + +def _rows_prefix(org_id: str, database_id: str) -> str: + return f"orgs/{org_id}/databases/{database_id}/rows/" + + +def _lookup_path(org_id: str, database_id: str, lookup_name: str) -> str: + return f"orgs/{org_id}/databases/{database_id}/lookups/{lookup_name}" + + +# --- Parsing ------------------------------------------------------------------ + +def _parse_csv(file_bytes: bytes) -> tuple[list[str], list[dict]]: + text = file_bytes.decode("utf-8-sig") + reader = csv.DictReader(io.StringIO(text)) + headers = list(reader.fieldnames or []) + return headers, [dict(row) for row in reader] + + +def _parse_json(file_bytes: bytes) -> tuple[list[str], list[dict]]: + data = json.loads(file_bytes.decode("utf-8")) + if isinstance(data, dict): + data = data.get("rows") or data.get("data") or list(data.values()) + if not isinstance(data, list) or not data or not all(isinstance(r, dict) for r in data): + raise ValidationError("JSON upload must be a non-empty array of objects") + headers = list(dict.fromkeys(k for row in data for k in row.keys())) + return headers, [{h: row.get(h) for h in headers} for row in data] + + +def _parse_xlsx(file_bytes: bytes) -> tuple[list[str], list[dict]]: + import openpyxl # only needed for this one branch โ€” keep the import lazy + + workbook = openpyxl.load_workbook(io.BytesIO(file_bytes), read_only=True, data_only=True) + sheet = workbook.active + rows_iter = sheet.iter_rows(values_only=True) + try: + header_row = next(rows_iter) + except StopIteration: + raise ValidationError("Spreadsheet has no rows") + headers = [str(h) if h is not None else "" for h in header_row] + rows = [ + {headers[i]: (r[i] if i < len(r) else None) for i in range(len(headers))} + for r in rows_iter + ] + return headers, rows + + +_PARSERS = {"csv": _parse_csv, "json": _parse_json, "xlsx": _parse_xlsx, "xls": _parse_xlsx} + + +def _clean(headers: list[str], rows: list[dict]) -> tuple[list[str], list[dict]]: + """Trims whitespace, drops blank/duplicate headers, drops fully-empty rows and columns.""" + deduped: list[str] = [] + seen: set[str] = set() + for h in headers: + h = (h or "").strip() + if not h: + continue + base, i = h, 1 + while h in seen: + i += 1 + h = f"{base}_{i}" + seen.add(h) + deduped.append(h) + + cleaned_rows = [] + for row in rows: + new_row = {h: (str(row.get(h)).strip() if row.get(h) not in (None, "") else "") for h in deduped} + if any(new_row.values()): + cleaned_rows.append(new_row) + + nonempty_cols = [h for h in deduped if any(r[h] for r in cleaned_rows)] + cleaned_rows = [{h: r[h] for h in nonempty_cols} for r in cleaned_rows] + return nonempty_cols, cleaned_rows + + +# --- Classification ------------------------------------------------------------- + +def _match_ratio(values: list[str], predicate) -> float: + nonempty = [v for v in values if v] + if not nonempty: + return 0.0 + return sum(1 for v in nonempty if predicate(v)) / len(nonempty) + + +_PERSON_HEADER_RE = re.compile(r"^(full |first |last |sur|given |your |participant |contact )?(name|surname|fullname)\b", re.IGNORECASE) + + +def _looks_like_person_name_header(header: str) -> bool: + """A header that merely *contains* "name" is often not a person ("Name of School / + Institution", "Username", "Company name"): only headers that lead with name-ish words count.""" + return bool(_PERSON_HEADER_RE.match(header.strip())) and not re.search( + r"\b(of|school|institution|organi[sz]ation|company|business|user|file|team|group)\b", header, re.IGNORECASE + ) + + +def classify_column(header: str, values: list[str]) -> str: + if _match_ratio(values, lambda v: bool(EMAIL_RE.match(v))) >= 0.6: + return "email" + if _match_ratio(values, lambda v: bool(URL_RE.match(v))) >= 0.6: + return "link" + if _match_ratio(values, lambda v: v.lower() in BOOL_VALUES) >= 0.9: + return "bool" + if _match_ratio(values, lambda v: bool(DATE_RE.match(v))) >= 0.6: + return "date" + if _match_ratio(values, lambda v: bool(PHONE_RE.match(v)) and not RANGE_RE.match(v)) >= 0.6: + return "contact" + if _match_ratio(values, lambda v: ";" in v) >= 0.3: + return "tag" + if _looks_like_person_name_header(header): + return "name" + return "text" + + +LIST_DELIMITERS = (";", ",", "|", "\n", "mixed") + + +def detect_list_delimiter(values: list[str]) -> str | None: + """Looks for a separator that makes this column a list of short items ("Acme, Beta Ltd"). + Returns the delimiter or None. Deliberately conservative: it only ever feeds a *suggestion* + the user confirms, because commas also appear in names ("Smith, John") and sentences.""" + nonempty = [v for v in values if v] + if len(nonempty) < 2: + return None + + def qualifies(delim: str) -> bool: + parts = [split_items(v, delim) for v in nonempty if (delim in v if delim != "mixed" else re.search(r"[;,|\n]", v))] + if len(parts) < 2 or len(parts) / len(nonempty) < 0.3: + return False + items = [i for p in parts for i in p] + if not items or any(len(i) > 60 for i in items): + return False + # Sentences have long "items"; lists of names/events/tags have short ones. + return sum(len(i.split()) for i in items) / len(items) <= 4 + + ratios = {d: sum(1 for v in nonempty if d in v) / len(nonempty) for d in (";", ",", "|", "\n")} + if ratios[";"] >= 0.2 and ratios[","] >= 0.2 and qualifies("mixed"): + return "mixed" + for delim in sorted(ratios, key=lambda d: -ratios[d]): + if ratios[delim] >= 0.3 and qualifies(delim): + return delim + return None + + +def _has_conforming_value(values: list[str], new_type: str) -> bool: + validator = TYPE_VALIDATORS.get(new_type) + if validator is None: + return True # name/tag/text have no syntax to conform to + nonempty = [v for v in values if v] + return not nonempty or any(validator(v) for v in nonempty) + + +def _flagged_values(values: list[str], col_type: str) -> list[int]: + validator = TYPE_VALIDATORS.get(col_type) + if validator is None: + return [] + return [i for i, v in enumerate(values) if v and not validator(v)] + + +def _assign_row_ids(rows: list[dict]) -> list[tuple[str, dict]]: + return [(uuid.uuid4().hex, row) for row in rows] + + +def _columns_with_flags(column_types: dict[str, str], headers: list[str], id_rows: list[tuple[str, dict]]) -> list[dict]: + """Flags non-conforming values up front, at classification time โ€” not only when a column's + type is changed later. An auto-classified "email" column with one bad row should show that + immediately, the same as a manual type change would.""" + columns = [] + for h in headers: + values = [row.get(h, "") for _, row in id_rows] + flagged_indices = _flagged_values(values, column_types[h]) + col = { + "name": h, + "type": column_types[h], + "flagged_row_ids": [id_rows[i][0] for i in flagged_indices], + } + if col["type"] == "tag": + col["delimiter"] = detect_list_delimiter(values) or ";" + elif col["type"] in ("text", "name"): + suggested = detect_list_delimiter(values) + if suggested: + col["list_suggestion"] = suggested + columns.append(col) + return columns + + +# --- Upload / create ------------------------------------------------------------ + +def create_database_from_upload( + org_id: str, actor_uid: str, name: str, file_bytes: bytes, filename: str, + save_copy=None, +) -> str: + """save_copy(database_id, ext, file_bytes) -> None is injected rather than hardcoded so + this stays unit-testable without touching disk; the real implementation lives in app.py's + route (writes to uploads/{org_id}/{database_id}.{ext}).""" + orgs.require_permission(org_id, actor_uid, "edit_lists") + + ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else "" + parser = _PARSERS.get(ext) + if parser is None: + raise ValidationError(f"Unsupported file type {filename!r} โ€” use .csv, .xlsx, or .json") + + headers, rows = parser(file_bytes) + headers, rows = _clean(headers, rows) + if not headers or not rows: + raise ValidationError("No usable data found in that file after cleaning") + + column_types = {h: classify_column(h, [r[h] for r in rows]) for h in headers} + identity_columns = {h for h in headers if column_types[h] in ("email", "contact")} + result = normalize.normalize(rows, headers, exclude_determinants=identity_columns, auto_split=False) + + database_id = uuid.uuid4().hex + if save_copy: + save_copy(database_id, ext, file_bytes) + + id_rows = _assign_row_ids(result.root.rows) + columns = _columns_with_flags(column_types, result.root.columns, id_rows) + + db.set_doc(_database_path(org_id, database_id), { + "name": name, + "source_filename": filename, + "source_kind": "xlsx" if ext in ("xlsx", "xls") else ext, + "created_at": _now(), + "row_count": len(result.root.rows), + "columns": columns, + "lookup_tables": [{"name": t.name, "columns": t.columns} for t in result.lookups], + "suggestions": result.suggestions, + }) + + for lookup in result.lookups: + db.set_doc(_lookup_path(org_id, database_id, lookup.name), { + "columns": lookup.columns, + "encrypted_rows": encrypt(json.dumps(lookup.rows)), + }) + + for row_id, row in id_rows: + db.set_doc(_row_path(org_id, database_id, row_id), {"encrypted_data": encrypt(json.dumps(row))}) + + return database_id + + +def get_database(org_id: str, database_id: str) -> dict: + doc = db.get_doc(_database_path(org_id, database_id)) + if doc is None: + raise orgs.NotFoundError(f"No database {database_id!r} in org {org_id!r}") + return doc + + +def list_databases(org_id: str) -> dict[str, dict]: + prefix = f"orgs/{org_id}/databases/" + docs = db.query_prefix(prefix) + return {path[len(prefix):]: data for path, data in docs.items()} + + +def list_rows(org_id: str, database_id: str, search: str | None = None, sort: str | None = None) -> list[dict]: + """Every row, decrypted, with its row_id โ€” client-side-sized (prototype scale), so search + and sort both happen here in Python rather than needing a real query engine.""" + prefix = _rows_prefix(org_id, database_id) + docs = db.query_prefix(prefix) + rows = [] + for path, data in docs.items(): + row = json.loads(decrypt(data["encrypted_data"])) + row["row_id"] = path[len(prefix):] + rows.append(row) + + if search: + needle = search.strip().lower() + rows = [r for r in rows if any(needle in str(v).lower() for v in r.values())] + + if sort: + rows.sort(key=lambda r: (r.get(sort) is None, str(r.get(sort, "")).lower())) + + return rows + + +# Operators a segment condition can use. Which ones make sense depends on the column's type โ€” +# SEGMENT_OPERATORS_BY_TYPE below is what the frontend uses to only offer valid ones, but +# _row_matches tolerates any operator against any column rather than erroring, since a changed +# column type shouldn't break a condition written before the change. +SEGMENT_OPERATORS_BY_TYPE: dict[str, tuple[str, ...]] = { + "bool": ("is_true", "is_false", "is_empty", "is_not_empty"), + "tag": ("has_tag", "lacks_tag", "is_empty", "is_not_empty"), +} +_DEFAULT_OPERATORS = ("equals", "not_equals", "contains", "not_contains", "is_empty", "is_not_empty") + + +def _row_matches(row: dict, col_type: str, field: str, op: str, value: str, delimiter: str | None = None) -> bool: + text = str(row.get(field, "") or "") + + if op == "is_empty": + return text.strip() == "" + if op == "is_not_empty": + return text.strip() != "" + + if col_type == "bool": + truthy = text.strip().lower() in {"true", "yes", "y", "1"} + if op == "is_true": + return truthy + if op == "is_false": + return not truthy + + if col_type == "tag": + tags = {t.lower() for t in split_items(text, delimiter)} + needle = value.strip().lower() + if op == "has_tag": + return needle in tags + if op == "lacks_tag": + return needle not in tags + + needle = value.strip().lower() + hay = text.strip().lower() + if op == "equals": + return hay == needle + if op == "not_equals": + return hay != needle + if op == "contains": + return needle in hay + if op == "not_contains": + return needle not in hay + return True + + +def apply_segment(rows: list[dict], columns: list[dict], conditions: list[dict]) -> list[dict]: + """Narrows `rows` to only those matching every condition (AND). Each condition is + {field, op, value}; unknown fields match nothing (a stale condition from a since-removed + column shouldn't silently widen a send back out to everyone).""" + col_types = {c["name"]: c["type"] for c in columns} + delimiters = {c["name"]: c.get("delimiter") for c in columns} + matched = rows + for cond in conditions: + field = cond.get("field", "") + if field not in col_types: + return [] + op = cond.get("op", "") + value = str(cond.get("value", "")) + col_type = col_types[field] + matched = [r for r in matched if _row_matches(r, col_type, field, op, value, delimiters[field])] + return matched + + +def preview_segment(org_id: str, database_id: str, conditions: list[dict]) -> dict: + """Live "how many recipients does this match" count for the campaign segment builder, plus + a small sample so the UI can show who, not just how many.""" + database = get_database(org_id, database_id) + rows = list_rows(org_id, database_id) + matched = apply_segment(rows, database["columns"], conditions) + return {"matched": len(matched), "sample": matched[:5]} + + +def add_row(org_id: str, actor_uid: str, database_id: str, values: dict) -> str: + orgs.require_permission(org_id, actor_uid, "edit_lists") + return insert_row(org_id, database_id, values) + + +def insert_row(org_id: str, database_id: str, values: dict) -> str: + """add_row without the role check โ€” for callers that have already authorized the insert + some other way (backend/collect.py: a confirmed double opt-in, not a signed-in user).""" + get_database(org_id, database_id) # raises NotFoundError if missing + row_id = uuid.uuid4().hex + db.set_doc(_row_path(org_id, database_id, row_id), {"encrypted_data": encrypt(json.dumps(values))}) + database = get_database(org_id, database_id) + db.update_doc(_database_path(org_id, database_id), {"row_count": database["row_count"] + 1}) + known = {c["name"] for c in database["columns"]} + new_cols = [k for k in values if k not in known] + if new_cols: + updated_columns = database["columns"] + [{"name": k, "type": "text", "flagged_row_ids": []} for k in new_cols] + db.update_doc(_database_path(org_id, database_id), {"columns": updated_columns}) + return row_id + + +def update_row(org_id: str, actor_uid: str, database_id: str, row_id: str, tags: dict) -> None: + """Merges `tags` into the row's existing values. Any key not already a known column is + appended to the database's column list (type "text") โ€” a manually-added tag becomes a + real, placeholder-usable column for the whole database, matching how the CSV-derived + columns work, not a side channel.""" + orgs.require_permission(org_id, actor_uid, "edit_lists") + path = _row_path(org_id, database_id, row_id) + doc = db.get_doc(path) + if doc is None: + raise orgs.NotFoundError(f"No row {row_id!r} in database {database_id!r}") + row = json.loads(decrypt(doc["encrypted_data"])) + row.update(tags) + db.set_doc(path, {"encrypted_data": encrypt(json.dumps(row))}) + + database = get_database(org_id, database_id) + known = {c["name"] for c in database["columns"]} + new_cols = [k for k in tags if k not in known] + if new_cols: + updated_columns = database["columns"] + [{"name": k, "type": "text", "flagged_row_ids": []} for k in new_cols] + db.update_doc(_database_path(org_id, database_id), {"columns": updated_columns}) + + +def bulk_update_rows(org_id: str, actor_uid: str, database_id: str, row_ids: list[str], tags: dict) -> list[str]: + """Same merge semantics as update_row, applied to many rows in one call โ€” the mass "fill a + column" / "add a tag to the selection" grid actions need this, since looping update_row + client-side would mean one HTTP round trip per selected row (unusable at a few thousand + rows). Fetches the database doc once up front and updates it once at the end, rather than + once per row like update_row does. Silently skips a row_id that no longer exists (e.g. a + stale selection from before a delete) instead of failing the whole batch over it.""" + orgs.require_permission(org_id, actor_uid, "edit_lists") + database = get_database(org_id, database_id) + + updated: list[str] = [] + for row_id in row_ids: + path = _row_path(org_id, database_id, row_id) + doc = db.get_doc(path) + if doc is None: + continue + row = json.loads(decrypt(doc["encrypted_data"])) + row.update(tags) + db.set_doc(path, {"encrypted_data": encrypt(json.dumps(row))}) + updated.append(row_id) + + known = {c["name"] for c in database["columns"]} + new_cols = [k for k in tags if k not in known] + if new_cols: + updated_columns = database["columns"] + [{"name": k, "type": "text", "flagged_row_ids": []} for k in new_cols] + db.update_doc(_database_path(org_id, database_id), {"columns": updated_columns}) + + return updated + + +def bulk_append_tag( + org_id: str, actor_uid: str, database_id: str, row_ids: list[str], tag: str, tag_column: str = "Tags", +) -> list[str]: + """Appends `tag` to the existing semicolon-delimited tag_column value for each row, rather + than overwriting it like bulk_update_rows does โ€” each row keeps whatever tags it already + had, so this can't be expressed as one uniform PATCH value the way a column "fill" can. + Still a single HTTP call for the whole selection, looping server-side rather than once per + row over the network.""" + orgs.require_permission(org_id, actor_uid, "edit_lists") + database = get_database(org_id, database_id) + + updated: list[str] = [] + for row_id in row_ids: + path = _row_path(org_id, database_id, row_id) + doc = db.get_doc(path) + if doc is None: + continue + row = json.loads(decrypt(doc["encrypted_data"])) + existing = [t for t in str(row.get(tag_column, "")).split(";") if t] + if tag not in existing: + existing.append(tag) + row[tag_column] = ";".join(existing) + db.set_doc(path, {"encrypted_data": encrypt(json.dumps(row))}) + updated.append(row_id) + + known = {c["name"] for c in database["columns"]} + if tag_column not in known: + updated_columns = database["columns"] + [{"name": tag_column, "type": "tag", "flagged_row_ids": []}] + db.update_doc(_database_path(org_id, database_id), {"columns": updated_columns}) + + return updated + + +def delete_rows(org_id: str, actor_uid: str, database_id: str, row_ids: list[str]) -> int: + """Bulk delete for the grid's mass-selection "Delete" action โ€” same one-call-not-N + reasoning as bulk_update_rows. Returns the number actually deleted (stale ids are skipped, + not errors) so the caller can show an accurate count.""" + orgs.require_permission(org_id, actor_uid, "edit_lists") + database = get_database(org_id, database_id) + + deleted = 0 + for row_id in row_ids: + path = _row_path(org_id, database_id, row_id) + if db.get_doc(path) is None: + continue + db.delete_doc(path) + deleted += 1 + + if deleted: + db.update_doc(_database_path(org_id, database_id), {"row_count": max(0, database["row_count"] - deleted)}) + + return deleted + + +def bulk_set_values(org_id: str, actor_uid: str, database_id: str, updates: dict[str, dict]) -> list[str]: + """Like bulk_update_rows, but each row gets its OWN value map rather than one uniform + value for everyone. This is what undoing a "fill column for N rows" needs โ€” each row's + prior value was (generally) different before the fill overwrote it, so restoring them + can't be expressed as a single uniform PATCH the way the fill itself was.""" + orgs.require_permission(org_id, actor_uid, "edit_lists") + database = get_database(org_id, database_id) + + updated: list[str] = [] + all_new_keys: set[str] = set() + for row_id, values in updates.items(): + path = _row_path(org_id, database_id, row_id) + doc = db.get_doc(path) + if doc is None: + continue + row = json.loads(decrypt(doc["encrypted_data"])) + row.update(values) + db.set_doc(path, {"encrypted_data": encrypt(json.dumps(row))}) + updated.append(row_id) + all_new_keys.update(values.keys()) + + known = {c["name"] for c in database["columns"]} + new_cols = [k for k in all_new_keys if k not in known] + if new_cols: + updated_columns = database["columns"] + [{"name": k, "type": "text", "flagged_row_ids": []} for k in new_cols] + db.update_doc(_database_path(org_id, database_id), {"columns": updated_columns}) + return updated + + +def remove_column(org_id: str, actor_uid: str, database_id: str, column: str) -> dict: + """Drops a column from the schema and strips it from every row. Returns a snapshot + ({column def, values_by_row_id}) so the caller (the grid's undo stack) can restore it + exactly via restore_column without a second round trip to reconstruct what was deleted.""" + orgs.require_permission(org_id, actor_uid, "edit_lists") + database = get_database(org_id, database_id) + col_def = next((c for c in database["columns"] if c["name"] == column), None) + if col_def is None: + raise orgs.NotFoundError(f"No column {column!r} in database {database_id!r}") + + values_by_row_id: dict[str, str] = {} + for row in list_rows(org_id, database_id): + row_id = row["row_id"] + if column not in row: + continue + values_by_row_id[row_id] = row[column] + remaining = {k: v for k, v in row.items() if k not in (column, "row_id")} + db.set_doc(_row_path(org_id, database_id, row_id), {"encrypted_data": encrypt(json.dumps(remaining))}) + + updated_columns = [c for c in database["columns"] if c["name"] != column] + db.update_doc(_database_path(org_id, database_id), {"columns": updated_columns}) + return {"column": col_def, "values_by_row_id": values_by_row_id} + + +def restore_column(org_id: str, actor_uid: str, database_id: str, column_def: dict, values_by_row_id: dict[str, str]) -> None: + """The inverse of remove_column โ€” undo target for the grid's "Remove column" action.""" + orgs.require_permission(org_id, actor_uid, "edit_lists") + database = get_database(org_id, database_id) + for row_id, value in values_by_row_id.items(): + path = _row_path(org_id, database_id, row_id) + doc = db.get_doc(path) + if doc is None: + continue + row = json.loads(decrypt(doc["encrypted_data"])) + row[column_def["name"]] = value + db.set_doc(path, {"encrypted_data": encrypt(json.dumps(row))}) + if not any(c["name"] == column_def["name"] for c in database["columns"]): + db.update_doc(_database_path(org_id, database_id), {"columns": database["columns"] + [column_def]}) + + +def rename_column(org_id: str, actor_uid: str, database_id: str, column: str, new_name: str) -> str: + """Renames a column in the schema and re-keys it in every row, keeping column order. No + values change, so renaming back is an exact undo. Saved presets and campaigns that use + {OldName} keep the old text; the UI warns about that.""" + orgs.require_permission(org_id, actor_uid, "edit_lists") + new_name = " ".join(new_name.split()) + if not new_name: + raise ValidationError("A column name can't be empty") + if new_name == "row_id": + raise ValidationError("That name is reserved") + database = get_database(org_id, database_id) + if not any(c["name"] == column for c in database["columns"]): + raise orgs.NotFoundError(f"No column {column!r} in database {database_id!r}") + if new_name == column: + return new_name + if any(c["name"].lower() == new_name.lower() for c in database["columns"] if c["name"] != column): + raise ValidationError(f"There is already a column called {new_name!r}") + + for row in list_rows(org_id, database_id): + if column not in row: + continue + rekeyed = {(new_name if k == column else k): v for k, v in row.items() if k != "row_id"} + db.set_doc(_row_path(org_id, database_id, row["row_id"]), {"encrypted_data": encrypt(json.dumps(rekeyed))}) + + updated_columns = [{**c, "name": new_name} if c["name"] == column else c for c in database["columns"]] + db.update_doc(_database_path(org_id, database_id), {"columns": updated_columns}) + return new_name + + +def column_rename_suggestions(org_id: str, database_id: str) -> list[dict]: + from backend import rename_suggest + + return rename_suggest.suggest_renames(get_database(org_id, database_id)["columns"]) + + +def column_type_suggestions(org_id: str, database_id: str) -> list[dict]: + """Columns whose stored type no longer matches what their values say (e.g. a date column + that an older classifier called "contact"). Only ever a suggestion; never applied unasked. + Only recommends moving between the plain, low-stakes types, so a column the person + deliberately set to email, list or yes/no is left alone.""" + database = get_database(org_id, database_id) + rows = list_rows(org_id, database_id) + suggestions = [] + for col in database["columns"]: + if col["type"] not in ("text", "contact", "name"): + continue + guess = classify_column(col["name"], [r.get(col["name"], "") for r in rows]) + if guess != col["type"] and guess in ("text", "date", "contact", "name", "email", "link", "bool"): + suggestions.append({"column": col["name"], "current": col["type"], "suggested": guess}) + return suggestions + + +def rename_database(org_id: str, actor_uid: str, database_id: str, new_name: str) -> None: + orgs.require_permission(org_id, actor_uid, "edit_lists") + get_database(org_id, database_id) + if not new_name.strip(): + raise ValidationError("Name can't be empty") + db.update_doc(_database_path(org_id, database_id), {"name": new_name.strip()}) + + +def set_database_disabled(org_id: str, actor_uid: str, database_id: str, disabled: bool) -> None: + """"Disabled" means excluded from campaign sends only โ€” still fully visible and editable + here. Doesn't cascade into blocking merges or anything else; that would be a separate, + more surprising rule than what the name implies.""" + orgs.require_permission(org_id, actor_uid, "edit_lists") + get_database(org_id, database_id) + db.update_doc(_database_path(org_id, database_id), {"disabled": disabled}) + + +def delete_database(org_id: str, actor_uid: str, database_id: str) -> None: + orgs.require_permission(org_id, actor_uid, "edit_lists") + get_database(org_id, database_id) + for path in list(db.query_prefix(_rows_prefix(org_id, database_id)).keys()): + db.delete_doc(path) + lookups_prefix = f"orgs/{org_id}/databases/{database_id}/lookups/" + for path in list(db.query_prefix(lookups_prefix).keys()): + db.delete_doc(path) + db.delete_doc(_database_path(org_id, database_id)) + + +def duplicate_database(org_id: str, actor_uid: str, database_id: str, new_name: str) -> str: + orgs.require_permission(org_id, actor_uid, "edit_lists") + database = get_database(org_id, database_id) + rows = list_rows(org_id, database_id) + new_id = uuid.uuid4().hex + id_map = {r["row_id"]: uuid.uuid4().hex for r in rows} + + db.set_doc(_database_path(org_id, new_id), {**database, "name": new_name, "created_at": _now()}) + for r in rows: + payload = {k: v for k, v in r.items() if k != "row_id"} + db.set_doc(_row_path(org_id, new_id, id_map[r["row_id"]]), {"encrypted_data": encrypt(json.dumps(payload))}) + + lookups_prefix = f"orgs/{org_id}/databases/{database_id}/lookups/" + for path, data in db.query_prefix(lookups_prefix).items(): + db.set_doc(_lookup_path(org_id, new_id, path[len(lookups_prefix):]), data) + + # re-point flagged_row_ids at the new row ids โ€” leaving them pointing at the OLD + # database's ids would silently flag the wrong rows (or none, once those ids never match). + updated_columns = [ + {**c, "flagged_row_ids": [id_map[rid] for rid in c["flagged_row_ids"] if rid in id_map]} + for c in database["columns"] + ] + db.update_doc(_database_path(org_id, new_id), {"columns": updated_columns}) + return new_id + + +def get_lookup_table(org_id: str, database_id: str, lookup_name: str) -> dict: + """Read-only access to a normalized lookup table's actual rows โ€” the database doc only + ever stores the lookup's NAME and column list (see create_database_from_upload), never its + rows, so the grid's lookup-table viewer needs a dedicated fetch rather than reading it off + the database doc it already has.""" + doc = db.get_doc(_lookup_path(org_id, database_id, lookup_name)) + if doc is None: + raise orgs.NotFoundError(f"No lookup table {lookup_name!r} in database {database_id!r}") + return {"columns": doc["columns"], "rows": json.loads(decrypt(doc["encrypted_rows"]))} + + +def set_column_list(org_id: str, actor_uid: str, database_id: str, column: str, delimiter: str | None) -> None: + """Makes `column` a list column split on `delimiter` (or, with None, dismisses the + suggestion to do so and leaves the column as it is).""" + orgs.require_permission(org_id, actor_uid, "edit_lists") + if delimiter is not None and delimiter not in LIST_DELIMITERS: + raise ValidationError(f"Unknown list separator {delimiter!r}") + database = get_database(org_id, database_id) + if not any(c["name"] == column for c in database["columns"]): + raise orgs.NotFoundError(f"No column {column!r} in database {database_id!r}") + updated = [] + for c in database["columns"]: + if c["name"] == column: + c = {k: v for k, v in c.items() if k != "list_suggestion"} + if delimiter is not None: + c = {**c, "type": "tag", "delimiter": delimiter, "flagged_row_ids": []} + updated.append(c) + db.update_doc(_database_path(org_id, database_id), {"columns": updated}) + + +def update_column_type(org_id: str, database_id: str, column: str, new_type: str) -> list[str]: + if new_type not in COLUMN_TYPES: + raise ValidationError(f"Unknown column type {new_type!r}") + database = get_database(org_id, database_id) + if not any(c["name"] == column for c in database["columns"]): + raise orgs.NotFoundError(f"No column {column!r} in database {database_id!r}") + + rows = list_rows(org_id, database_id) + values = [r.get(column, "") for r in rows] + if not _has_conforming_value(values, new_type): + raise ValidationError( + f"No existing value in {column!r} looks like a valid {new_type} โ€” refusing the change" + ) + + flagged_indices = _flagged_values(values, new_type) + flagged_row_ids = [rows[i]["row_id"] for i in flagged_indices] + + updated_columns = [ + {**{k: v for k, v in c.items() if k != "list_suggestion"}, "type": new_type, "flagged_row_ids": flagged_row_ids, + **({"delimiter": c.get("delimiter") or ";"} if new_type == "tag" else {})} + if c["name"] == column else c + for c in database["columns"] + ] + db.update_doc(_database_path(org_id, database_id), {"columns": updated_columns}) + return flagged_row_ids + + +def merge_databases(org_id: str, actor_uid: str, database_id_a: str, database_id_b: str, new_name: str) -> str: + """Concatenates both databases' rows under a brand-new database, reconciling columns by + name (union) and re-running classification + normalization over the combined set โ€” a + merge isn't just a row concat, it's a fresh upload of the combined data.""" + orgs.require_permission(org_id, actor_uid, "edit_lists") + rows_a = list_rows(org_id, database_id_a) + rows_b = list_rows(org_id, database_id_b) + headers = list(dict.fromkeys([k for r in rows_a + rows_b for k in r if k != "row_id"])) + + # Exact-duplicate rows (e.g. the same contact present in both databases) are dropped + # before normalizing โ€” besides being the obviously-wanted merge behavior on its own, an + # un-deduplicated duplicate row makes EVERY column pair look like a valid functional + # dependency (they trivially agree with their own duplicate), which would otherwise send + # the FD-discovery heuristic down a false trail. + seen_rows: set[tuple] = set() + combined: list[dict] = [] + for r in rows_a + rows_b: + row = {h: r.get(h, "") for h in headers} + key = tuple(row[h] for h in headers) + if key in seen_rows: + continue + seen_rows.add(key) + combined.append(row) + + column_types = {h: classify_column(h, [r[h] for r in combined]) for h in headers} + identity_columns = {h for h in headers if column_types[h] in ("email", "contact")} + result = normalize.normalize(combined, headers, exclude_determinants=identity_columns, auto_split=False) + + database_id = uuid.uuid4().hex + id_rows = _assign_row_ids(result.root.rows) + columns = _columns_with_flags(column_types, result.root.columns, id_rows) + + db.set_doc(_database_path(org_id, database_id), { + "name": new_name, + "source_filename": f"merge({database_id_a[:8]}, {database_id_b[:8]})", + "source_kind": "merge", + "created_at": _now(), + "row_count": len(result.root.rows), + "columns": columns, + "lookup_tables": [{"name": t.name, "columns": t.columns} for t in result.lookups], + "suggestions": result.suggestions, + }) + for lookup in result.lookups: + db.set_doc(_lookup_path(org_id, database_id, lookup.name), { + "columns": lookup.columns, + "encrypted_rows": encrypt(json.dumps(lookup.rows)), + }) + for row_id, row in id_rows: + db.set_doc(_row_path(org_id, database_id, row_id), {"encrypted_data": encrypt(json.dumps(row))}) + return database_id diff --git a/backend/delivery.py b/backend/delivery.py new file mode 100644 index 0000000000000000000000000000000000000000..0e07a123a872fca01015642a9a8cd4f44c630feb --- /dev/null +++ b/backend/delivery.py @@ -0,0 +1,291 @@ +""" +What happened to a message after the mailbox's server accepted it. + +SMTP only tells us the provider took the message. A provider may then hold it for an hour or more +(traffic, throttling) and a person reading "sent" cannot tell that from a lost message. The +mailbox's IMAP side shows what comes back: delay notices, bounce notices and replies. This module +reads those and records one state per recipient: + + accepted The provider took it. Nothing has come back. This is all SMTP can prove. + delayed The provider (or the next server) says it is still trying. + bounced A failure notice came back for this message. + replied The person answered. + +IMAP cannot prove a message reached an inbox, so nothing here says "delivered". After a day with +nothing reported, the screen says "no problems reported", which is what is actually known. +""" + +from __future__ import annotations + +import email +import imaplib +import logging +import re +import ssl +from datetime import datetime, timedelta, timezone +from email import policy + +from backend import firestore_client as db + +log = logging.getLogger(__name__) + +ACCEPTED, DELAYED, BOUNCED, REPLIED = "accepted", "delayed", "bounced", "replied" +# A later state replaces an earlier one; a bounce is never overwritten by a delay notice. +_RANK = {ACCEPTED: 0, DELAYED: 1, REPLIED: 2, BOUNCED: 3} + +WATCH_DAYS = 3 +RECHECK_MINUTES = 10 +QUIET_AFTER_HOURS = 24 +MAX_MESSAGES_READ = 400 + +IMAP_PORT = 993 + +_ID = re.compile(r"<([^<>\s]+)>") +_DELAY_WORDS = re.compile(r"delay|still trying|will keep trying|not yet delivered|warning", re.I) +_BOUNCE_WORDS = re.compile(r"undeliver|failure|failed|returned|bounce|could not be delivered|couldn't be delivered|rejected|no such user", re.I) +_BOUNCE_SENDERS = re.compile(r"mailer-daemon|postmaster|mail delivery", re.I) + + +def imap_details(credentials: dict) -> dict | None: + """The IMAP server and sign-in saved for a mailbox, or None when none was given. + The IMAP user and password default to the SMTP ones, which is usual for one mailbox.""" + host = str(credentials.get("imap_host") or "").strip() + if not host: + return None + return { + "host": host, + "port": int(credentials.get("imap_port") or IMAP_PORT), + "username": str(credentials.get("imap_username") or credentials.get("username") or "").strip(), + "password": "".join(str(credentials.get("imap_password") or credentials.get("password") or "").split()), + } + + +def _ids_in(text: str) -> set[str]: + return {m.group(1) for m in _ID.finditer(text or "")} + + +def _text_of(msg) -> str: + """Every readable part of a notice, including the returned original, for finding our ids.""" + out = [] + for part in msg.walk(): + if part.get_content_type() in ("message/rfc822", "text/rfc822-headers", "message/delivery-status"): + for sub in part.iter_parts() if part.is_multipart() else []: + out.append(str(sub)) + elif part.get_content_maintype() == "text": + try: + out.append(part.get_content()) + except (LookupError, UnicodeDecodeError): + payload = part.get_payload(decode=True) or b"" + out.append(payload.decode("utf-8", errors="replace")) + return "\n".join(out) + + +def classify(raw: bytes, known_ids: set[str]) -> list[tuple[str, str]]: + """Reads one message from the mailbox and returns [(our message id, state)] for each of our + messages it is about. Ordinary mail that is about none of them returns [].""" + try: + msg = email.message_from_bytes(raw, policy=policy.default) + except Exception: # a malformed message is skipped, never fatal + return [] + subject = str(msg.get("Subject", "")) + sender = str(msg.get("From", "")) + notice = ( + msg.get_content_type() == "multipart/report" + or bool(_BOUNCE_SENDERS.search(sender)) + or bool(re.search(r"delivery status|undeliver|returned mail|failure notice", subject, re.I)) + ) + if notice: + body = _text_of(msg) + mentioned = _ids_in(body + "\n" + subject) & known_ids + if not mentioned: + return [] + action = re.search(r"^Action:\s*(\w+)", body, re.I | re.M) + verdict = (action.group(1).lower() if action else "") + if verdict == "delayed": + state = DELAYED + elif verdict == "failed": + state = BOUNCED + elif _BOUNCE_WORDS.search(subject): + state = BOUNCED + elif _DELAY_WORDS.search(subject): + state = DELAYED + else: + state = BOUNCED + return [(mid, state) for mid in mentioned] + + # Out-of-office and other automatic answers are not a person replying. + auto = str(msg.get("Auto-Submitted", "no")).lower() + if auto != "no" or str(msg.get("Precedence", "")).lower() in ("bulk", "junk", "auto_reply"): + return [] + replied_to = _ids_in(str(msg.get("In-Reply-To", "")) + " " + str(msg.get("References", ""))) & known_ids + return [(mid, REPLIED) for mid in replied_to] + + +class ImapInbox: + """A short read-only visit to a mailbox's IMAP server.""" + + def __init__(self, details: dict): + self._imap = imaplib.IMAP4_SSL(details["host"], details["port"], ssl_context=ssl.create_default_context(), timeout=20) + self._imap.login(details["username"], details["password"]) + + def recent(self, since: datetime, limit: int = MAX_MESSAGES_READ) -> list[bytes]: + """Raw messages that arrived since `since`, newest first, from the inbox and junk folders.""" + out: list[bytes] = [] + for folder in self._folders(): + status, _ = self._imap.select(f'"{folder}"', readonly=True) + if status != "OK": + continue + status, data = self._imap.search(None, "SINCE", since.strftime("%d-%b-%Y")) + if status != "OK" or not data or not data[0]: + continue + for num in reversed(data[0].split()[-limit:]): + status, parts = self._imap.fetch(num, "(BODY.PEEK[])") + if status == "OK" and parts and isinstance(parts[0], tuple): + out.append(parts[0][1]) + if len(out) >= limit: + return out + return out + + def _folders(self) -> list[str]: + names = ["INBOX"] + status, lines = self._imap.list() + if status == "OK": + for line in lines or []: + text = line.decode(errors="replace") if isinstance(line, bytes) else str(line) + if "\\junk" in text.lower(): + name = text.rsplit(' "', 1)[-1].strip('"') if ' "' in text else text.split()[-1] + names.append(name.strip('"')) + return names + + def close(self) -> None: + try: + self._imap.logout() + except (imaplib.IMAP4.error, OSError): + pass + + +def open_inbox(details: dict) -> ImapInbox: + """Separate so tests can stand in for a mailbox.""" + return ImapInbox(details) + + +def _watch_path(org_id: str, send_id: str) -> str: + return f"watch_sends/{org_id}__{send_id}" + + +def watch(org_id: str, send_id: str) -> None: + """Asks for this send's recipients to be checked for a few days.""" + until = (datetime.now(timezone.utc) + timedelta(days=WATCH_DAYS)).isoformat() + db.set_doc(_watch_path(org_id, send_id), {"org_id": org_id, "send_id": send_id, "until": until}) + + +def shown_state(record: dict, now: datetime | None = None, tracking: bool = True) -> dict: + """What to show for one recipient: {state, label, note}. `tracking` is False when the mailbox + has no IMAP details, which is said plainly instead of implying all is well.""" + now = now or datetime.now(timezone.utc) + status = record.get("status") + if status != "sent": + return {"state": status, "label": None, "note": None} + state = record.get("delivery") or ACCEPTED + if state == BOUNCED: + return {"state": state, "label": "Bounced", "note": record.get("delivery_note") or "The receiving server sent it back."} + if state == REPLIED: + return {"state": state, "label": "Replied", "note": None} + if state == DELAYED: + return {"state": state, "label": "Delayed at your provider", "note": "Your provider or the receiving server is still trying. This is not an error."} + if not tracking: + return {"state": state, "label": "Accepted by your provider", "note": "Add the IMAP details to this mailbox to see delays, bounces and replies."} + try: + age = now - datetime.fromisoformat(record.get("at")) + except (TypeError, ValueError): + age = timedelta(0) + if age >= timedelta(hours=QUIET_AFTER_HOURS) and record.get("delivery_checked"): + return {"state": state, "label": "Accepted, no problems reported", "note": None} + return {"state": state, "label": "Accepted by your provider", "note": "Providers sometimes hold mail for an hour or more before passing it on."} + + +def check_send(org_id: str, send_id: str, now: datetime | None = None) -> dict: + """Reads the mailbox's IMAP side once and updates each recipient of this send. Returns + {checked, bounced, delayed, replied, reason}. Never raises for a mailbox problem.""" + from backend import mailboxes, sending # imported here: both import this module's neighbours + + now = now or datetime.now(timezone.utc) + send = sending.get_send(org_id, send_id) + records = send.get("per_recipient") or {} + wanted = {r["reference"].strip("<>"): row_id for row_id, r in records.items() if r.get("status") == "sent" and r.get("reference")} + result = {"checked": False, "bounced": 0, "delayed": 0, "replied": 0, "reason": ""} + if not wanted: + result["reason"] = "nothing_to_check" + return result + try: + credentials = mailboxes.get_decrypted_credentials(org_id, send["mailbox_connection_id"]) + except Exception: + result["reason"] = "mailbox_missing" + return result + details = imap_details(credentials) + if details is None: + result["reason"] = "imap_missing" + return result + try: + started = min(datetime.fromisoformat(r["at"]) for r in records.values() if r.get("at")) + except ValueError: + started = now - timedelta(days=1) + inbox = None + try: + inbox = open_inbox(details) + raws = inbox.recent(started - timedelta(days=1)) + except (imaplib.IMAP4.error, OSError) as exc: + log.info("IMAP check failed for %s: %r", send_id, exc) + result["reason"] = "imap_failed" + return result + finally: + if inbox is not None: + inbox.close() + + found: dict[str, str] = {} + for raw in raws: + for mid, state in classify(raw, set(wanted)): + if _RANK[state] > _RANK.get(found.get(mid, ACCEPTED), 0): + found[mid] = state + stamp = now.isoformat() + for mid, row_id in wanted.items(): + record = dict(records[row_id]) + record["delivery_checked"] = stamp + state = found.get(mid) + if state and _RANK[state] >= _RANK.get(record.get("delivery") or ACCEPTED, 0): + record["delivery"] = state + record["delivery_at"] = stamp + result[state] = result.get(state, 0) + 1 + records[row_id] = record + db.update_doc(f"orgs/{org_id}/sends/{send_id}", {"per_recipient": records}) + result["checked"] = True + return result + + +def run_due(now: datetime | None = None, budget_seconds: float = 60) -> dict: + """Checks watched sends that have not been looked at for a few minutes. Real mailboxes only.""" + import time + + from backend import mailer_client # here: mailer_client imports the SMTP mailer, which imports this module + + if not mailer_client.real_send_enabled(): + return {"checked": 0} + now = now or datetime.now(timezone.utc) + started = time.monotonic() + done = 0 + for path, doc in list(db.query_prefix("watch_sends/").items()): + if time.monotonic() - started > budget_seconds: + break + if datetime.fromisoformat(doc["until"]) < now: + db.delete_doc(path) + continue + last = doc.get("last_check") + if last and now - datetime.fromisoformat(last) < timedelta(minutes=RECHECK_MINUTES): + continue + try: + check_send(doc["org_id"], doc["send_id"], now) + except Exception: # one bad send must not stop the rest + log.exception("Delivery check failed for %s", doc.get("send_id")) + db.update_doc(path, {"last_check": now.isoformat()}) + done += 1 + return {"checked": done} diff --git a/backend/dns_check.py b/backend/dns_check.py new file mode 100644 index 0000000000000000000000000000000000000000..47d6237bbc3dd5d2503e69700b5b00f85c34454a --- /dev/null +++ b/backend/dns_check.py @@ -0,0 +1,71 @@ +""" +Looks up a domain's email records (SPF, DKIM, DMARC, MX) so Settings > Advanced can say +what is already set up instead of only describing it. + +Uses a public DNS-over-HTTPS resolver, so it needs no extra library. DKIM records live +under a "selector" name chosen by the mail provider; there is no way to list them, so the +common selectors are tried and "not found" only means none of those exist. +""" + +from __future__ import annotations + +import json +import re +import urllib.parse +import urllib.request + +_RESOLVER = "https://dns.google/resolve" +_DOMAIN = re.compile(r"^(?=.{3,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$") +DKIM_SELECTORS = ("default", "google", "selector1", "selector2", "k1", "k2", "mail", "dkim", "s1", "s2", "x", "zoho", "mx") + + +def _lookup(name: str, rtype: str) -> list[str]: + url = f"{_RESOLVER}?{urllib.parse.urlencode({'name': name, 'type': rtype})}" + with urllib.request.urlopen(url, timeout=6) as resp: # noqa: S310 โ€” fixed https resolver + data = json.load(resp) + return [a["data"].strip('"').replace('" "', "") for a in data.get("Answer", []) if a.get("type") in (1, 5, 15, 16)] + + +def check_domain(domain: str, lookup=_lookup) -> dict: + """{domain, spf, dkim, dmarc, mx}. Each item is {ok, value, note}; ok is None when + the lookup itself failed (no answer either way).""" + domain = (domain or "").strip().lower() + if not _DOMAIN.match(domain): + raise ValueError("Enter a domain like yourcompany.com") + + def safe(name: str, rtype: str) -> list[str] | None: + try: + return lookup(name, rtype) + except Exception: # noqa: BLE001 โ€” network trouble is reported, not raised + return None + + result: dict = {"domain": domain} + txt = safe(domain, "TXT") + spf = [t for t in txt or [] if t.lower().startswith("v=spf1")] + result["spf"] = ( + {"ok": None, "value": "", "note": "We couldn't look this up. Try again."} if txt is None + else {"ok": len(spf) == 1, "value": spf[0] if spf else "", + "note": "Found." if len(spf) == 1 else "More than one SPF record. Mail servers need exactly one." if spf else "No SPF record."} + ) + dmarc_txt = safe(f"_dmarc.{domain}", "TXT") + dmarc = [t for t in dmarc_txt or [] if t.lower().startswith("v=dmarc1")] + result["dmarc"] = ( + {"ok": None, "value": "", "note": "We couldn't look this up. Try again."} if dmarc_txt is None + else {"ok": bool(dmarc), "value": dmarc[0] if dmarc else "", "note": "Found." if dmarc else "No DMARC record."} + ) + found = None + for selector in DKIM_SELECTORS: + records = safe(f"{selector}._domainkey.{domain}", "TXT") or [] + if any("p=" in r for r in records): + found = selector + break + result["dkim"] = ( + {"ok": True, "value": f"{found}._domainkey", "note": f"Found under the name {found}."} if found + else {"ok": False, "value": "", "note": "Not found under the usual names. Your provider may use another name; check with them."} + ) + mx = safe(domain, "MX") + result["mx"] = ( + {"ok": None, "value": "", "note": "We couldn't look this up. Try again."} if mx is None + else {"ok": bool(mx), "value": ", ".join(mx[:3]), "note": "Found." if mx else "No mail servers listed, so replies can't arrive."} + ) + return result diff --git a/backend/email_parts.py b/backend/email_parts.py new file mode 100644 index 0000000000000000000000000000000000000000..da74f04a33e59d6cb20d2dc8e08b493b80699bda --- /dev/null +++ b/backend/email_parts.py @@ -0,0 +1,100 @@ +""" +The parts of an email beyond its HTML: files attached to every copy, and images the sender +uploaded into the message itself. + +Uploaded images arrive in the HTML as data: URIs, which Gmail and most clients refuse to show. +extract_inline_images swaps each one for a cid: reference and returns the image bytes, so the +mailer can send them as inline parts of the same message. No image hosting is needed. +""" + +from __future__ import annotations + +import base64 +import binascii +import re +from dataclasses import dataclass + +MAX_ATTACHMENTS = 10 +MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024 +MAX_TOTAL_ATTACHMENT_BYTES = 20 * 1024 * 1024 +MAX_INLINE_IMAGES = 20 + +_DATA_URI_RE = re.compile( + r"""(src\s*=\s*["'])data:image/(png|jpe?g|gif|webp);base64,([A-Za-z0-9+/=\s]+)(["'])""", + re.IGNORECASE, +) +_UNSAFE_FILENAME_RE = re.compile(r'[\\/:*?"<>|\r\n\t]+') + + +@dataclass +class Attachment: + filename: str + content_type: str + data: bytes + + +@dataclass +class InlineImage: + cid: str + subtype: str + data: bytes + + +def safe_filename(name: str, fallback: str = "file") -> str: + cleaned = _UNSAFE_FILENAME_RE.sub(" ", name).strip(" .") + return cleaned[:150] or fallback + + +def decode_attachments(items: list[dict] | None) -> list[Attachment]: + """Turns the request's [{filename, content_type, data_b64}] into Attachments, enforcing the + count and size limits. Raises ValueError with a message the sender can act on.""" + if not items: + return [] + if len(items) > MAX_ATTACHMENTS: + raise ValueError(f"Attach at most {MAX_ATTACHMENTS} files") + out: list[Attachment] = [] + total = 0 + for item in items: + filename = safe_filename(str(item.get("filename") or ""), "attachment") + try: + data = base64.b64decode(item.get("data_b64") or "", validate=True) + except (binascii.Error, ValueError) as exc: + raise ValueError(f"{filename} could not be read") from exc + if not data: + raise ValueError(f"{filename} is empty") + if len(data) > MAX_ATTACHMENT_BYTES: + raise ValueError(f"{filename} is larger than 10 MB") + total += len(data) + content_type = str(item.get("content_type") or "application/octet-stream") + if "/" not in content_type: + content_type = "application/octet-stream" + out.append(Attachment(filename=filename, content_type=content_type, data=data)) + if total > MAX_TOTAL_ATTACHMENT_BYTES: + raise ValueError("Attachments add up to more than 20 MB") + return out + + +def extract_inline_images(html: str) -> tuple[str, list[InlineImage]]: + """Replaces every data:image src in `html` with a cid: reference. Identical images share one + part. Raises ValueError when there are too many, so a send never silently drops one.""" + images: list[InlineImage] = [] + seen: dict[str, str] = {} + + def swap(m: re.Match) -> str: + payload = re.sub(r"\s+", "", m.group(3)) + cid = seen.get(payload) + if cid is None: + try: + data = base64.b64decode(payload, validate=True) + except (binascii.Error, ValueError): + return m.group(0) + cid = f"m8img{len(images) + 1}@m8ion" + subtype = m.group(2).lower().replace("jpg", "jpeg") + images.append(InlineImage(cid=cid, subtype=subtype, data=data)) + seen[payload] = cid + return f"{m.group(1)}cid:{cid}{m.group(4)}" + + out = _DATA_URI_RE.sub(swap, html) + if len(images) > MAX_INLINE_IMAGES: + raise ValueError(f"Use at most {MAX_INLINE_IMAGES} images in one message") + return out, images diff --git a/backend/firebase_app.py b/backend/firebase_app.py new file mode 100644 index 0000000000000000000000000000000000000000..50874d1ed981742c334cce312bef53a39d949a14 --- /dev/null +++ b/backend/firebase_app.py @@ -0,0 +1,62 @@ +""" +Single shared firebase_admin App instance. backend/firestore_client.py (real Firestore +branch) and backend/auth.py (real token verification) both use this instead of each +initializing their own โ€” firebase_admin.initialize_app() raises if called twice for the +same app name, so this is a real requirement, not just tidiness. + +Only imported/called when LOCAL_MODE=false or REAL_AUTH_ENABLED=true โ€” never during the +test suite (backend/tests/conftest.py forces both off), so tests never need real credentials. +""" + +from __future__ import annotations + +import json +import os +import re + +import firebase_admin +from firebase_admin import credentials + +_app: firebase_admin.App | None = None + +_PEM_HEAD = "-----BEGIN PRIVATE KEY-----" +_PEM_TAIL = "-----END PRIVATE KEY-----" +_PEM = re.compile(r"-----BEGIN\s*PRIVATE\s*KEY-----(.*?)-----END\s*PRIVATE\s*KEY-----", re.S) + + +def service_account_info(raw: str) -> dict: + """ + Reads the key from the text of FIREBASE_SERVICE_ACCOUNT_JSON. Pasting a key into a host's + secret box often damages the line breaks inside "private_key" (they become the two characters + \\n, or spaces), and the key then cannot be read at all. Repair that here instead of failing. + """ + text = raw.strip() + if len(text) > 1 and text[0] == text[-1] and text[0] in "'\"": + text = text[1:-1] + info = json.loads(text, strict=False) + key = str(info.get("private_key", "")).replace("\\n", "\n") + # Rebuild the key from its body. The header may have lost its spaces too + # ("-----BEGINPRIVATEKEY-----") when every space was stripped from the pasted text. + found = _PEM.search(key) + if found: + body = "".join(found.group(1).split()) + lines = [body[i:i + 64] for i in range(0, len(body), 64)] + key = "\n".join([_PEM_HEAD, *lines, _PEM_TAIL]) + "\n" + info["private_key"] = key + return info + + +def get_app() -> firebase_admin.App: + global _app + if _app is None: + # A host that only offers environment variables (the Hugging Face Space) passes the key's + # content in FIREBASE_SERVICE_ACCOUNT_JSON; a developer's machine points at the file. + key_json = os.getenv("FIREBASE_SERVICE_ACCOUNT_JSON", "").strip() + if key_json: + cred = credentials.Certificate(service_account_info(key_json)) + else: + cred = credentials.Certificate( + os.getenv("GOOGLE_APPLICATION_CREDENTIALS", "./secrets/firebase-service-account.dev.json") + ) + _app = firebase_admin.initialize_app(cred) + return _app diff --git a/backend/firestore_client.py b/backend/firestore_client.py new file mode 100644 index 0000000000000000000000000000000000000000..e8cb79d25bee5efc0ba00b812d4324eef713e6b6 --- /dev/null +++ b/backend/firestore_client.py @@ -0,0 +1,71 @@ +""" +The single seam between the org/role model (and everything else that stores operational +metadata) and its actual backing store. Every caller uses get_doc/set_doc/update_doc/ +delete_doc/query_prefix from THIS module, never backend.local_store or the real Firestore +client directly. + +LOCAL_MODE governs which backing store this module uses โ€” real Firestore (a real GCP +project + service-account credential now exist, see backend/firebase_app.py) when false, +the local SQLite shim when true (the default in tests โ€” see tests/conftest.py, which forces +LOCAL_MODE=true regardless of .env so the suite never touches real Firestore). + +Firestore's own Python client accepts the same slash-delimited path strings our path scheme +already uses (`db.document("orgs/abc123")`, `db.collection("orgs/abc123/mailboxes")`) โ€” no +translation layer needed between our path convention and Firestore's. +""" + +from __future__ import annotations + +from firebase_admin import firestore + +from backend import local_store +from backend.firebase_app import get_app +from backend.local_mode import LOCAL_MODE + + +def _db(): + get_app() + return firestore.client() + + +def get_doc(path: str) -> dict | None: + if LOCAL_MODE: + return local_store.get_doc(path) + snap = _db().document(path).get() + return snap.to_dict() if snap.exists else None + + +def set_doc(path: str, data: dict) -> None: + if LOCAL_MODE: + local_store.set_doc(path, data) + return + _db().document(path).set(data) + + +def update_doc(path: str, partial: dict) -> dict: + """Shared across both backends: read-modify-write via this module's own get_doc/ + set_doc, so the merge semantics (raise if the doc doesn't exist) stay identical + regardless of which store is active โ€” no need to duplicate the logic per backend.""" + 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: + if LOCAL_MODE: + local_store.delete_doc(path) + return + _db().document(path).delete() + + +def query_prefix(prefix: str) -> dict[str, dict]: + """All documents under a collection path (e.g. "orgs/abc123/mailboxes/"), keyed by + their full path โ€” matches local_store.query_prefix's contract exactly.""" + if LOCAL_MODE: + return local_store.query_prefix(prefix) + collection_path = prefix.rstrip("/") + docs = _db().collection(collection_path).stream() + return {f"{collection_path}/{doc.id}": doc.to_dict() for doc in docs} diff --git a/backend/fonts/DejaVuSans-Bold.ttf b/backend/fonts/DejaVuSans-Bold.ttf new file mode 100644 index 0000000000000000000000000000000000000000..39699bd84ae17507955ce571caa859ad14997f4e --- /dev/null +++ b/backend/fonts/DejaVuSans-Bold.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b184b89e3c1075f22f6b71575b6fc20d4972b3cfd3b23322ca6fd596dcaef167 +size 704128 diff --git a/backend/fonts/DejaVuSans.ttf b/backend/fonts/DejaVuSans.ttf new file mode 100644 index 0000000000000000000000000000000000000000..f47aa8cffd396d3ac221ad7a2a518bc9a554c9ce --- /dev/null +++ b/backend/fonts/DejaVuSans.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3fdf69cabf06049ea70a00b5919340e2ce1e6d02b0cc3c4b44fb6801bd1e0d22 +size 756072 diff --git a/backend/fonts/DejaVuSerif.ttf b/backend/fonts/DejaVuSerif.ttf new file mode 100644 index 0000000000000000000000000000000000000000..73a4204e08a49a83ab7336cb55add8b32200ae24 --- /dev/null +++ b/backend/fonts/DejaVuSerif.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:107244956e9962b9e96faccdc551825e0ae0898ae13737133e1b921a2fd35ffa +size 379740 diff --git a/backend/fonts/IMFellEnglishSC-Regular.ttf b/backend/fonts/IMFellEnglishSC-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..9be01a0ad9589a04a193cec151cab01e0f78a13f --- /dev/null +++ b/backend/fonts/IMFellEnglishSC-Regular.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bfcbaf94bafb9843518e55034449b6c7f796cef0b3f6c36985c2eb1cde7b55e0 +size 180328 diff --git a/backend/fonts/LICENSE_DEJAVU.txt b/backend/fonts/LICENSE_DEJAVU.txt new file mode 100644 index 0000000000000000000000000000000000000000..254e2cc42a6d0135cccf2047768b9e44f25e666f --- /dev/null +++ b/backend/fonts/LICENSE_DEJAVU.txt @@ -0,0 +1,99 @@ +Fonts are (c) Bitstream (see below). DejaVu changes are in public domain. +Glyphs imported from Arev fonts are (c) Tavmjong Bah (see below) + +Bitstream Vera Fonts Copyright +------------------------------ + +Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is +a trademark of Bitstream, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of the fonts accompanying this license ("Fonts") and associated +documentation files (the "Font Software"), to reproduce and distribute the +Font Software, including without limitation the rights to use, copy, merge, +publish, distribute, and/or sell copies of the Font Software, and to permit +persons to whom the Font Software is furnished to do so, subject to the +following conditions: + +The above copyright and trademark notices and this permission notice shall +be included in all copies of one or more of the Font Software typefaces. + +The Font Software may be modified, altered, or added to, and in particular +the designs of glyphs or characters in the Fonts may be modified and +additional glyphs or characters may be added to the Fonts, only if the fonts +are renamed to names not containing either the words "Bitstream" or the word +"Vera". + +This License becomes null and void to the extent applicable to Fonts or Font +Software that has been modified and is distributed under the "Bitstream +Vera" names. + +The Font Software may be sold as part of a larger software package but no +copy of one or more of the Font Software typefaces may be sold by itself. + +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, +TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME +FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING +ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF +THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE +FONT SOFTWARE. + +Except as contained in this notice, the names of Gnome, the Gnome +Foundation, and Bitstream Inc., shall not be used in advertising or +otherwise to promote the sale, use or other dealings in this Font Software +without prior written authorization from the Gnome Foundation or Bitstream +Inc., respectively. For further information, contact: fonts at gnome dot +org. + +Arev Fonts Copyright +------------------------------ + +Copyright (c) 2006 by Tavmjong Bah. All Rights Reserved. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of the fonts accompanying this license ("Fonts") and +associated documentation files (the "Font Software"), to reproduce +and distribute the modifications to the Bitstream Vera Font Software, +including without limitation the rights to use, copy, merge, publish, +distribute, and/or sell copies of the Font Software, and to permit +persons to whom the Font Software is furnished to do so, subject to +the following conditions: + +The above copyright and trademark notices and this permission notice +shall be included in all copies of one or more of the Font Software +typefaces. + +The Font Software may be modified, altered, or added to, and in +particular the designs of glyphs or characters in the Fonts may be +modified and additional glyphs or characters may be added to the +Fonts, only if the fonts are renamed to names not containing either +the words "Tavmjong Bah" or the word "Arev". + +This License becomes null and void to the extent applicable to Fonts +or Font Software that has been modified and is distributed under the +"Tavmjong Bah Arev" names. + +The Font Software may be sold as part of a larger software package but +no copy of one or more of the Font Software typefaces may be sold by +itself. + +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL +TAVMJONG BAH BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + +Except as contained in this notice, the name of Tavmjong Bah shall not +be used in advertising or otherwise to promote the sale, use or other +dealings in this Font Software without prior written authorization +from Tavmjong Bah. For further information, contact: tavmjong @ free +. fr. + +$Id: LICENSE 2133 2007-11-28 02:46:28Z lechimp $ diff --git a/backend/fonts/README.md b/backend/fonts/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a2220e06c1ce97b44203e50e494223df63edd28c --- /dev/null +++ b/backend/fonts/README.md @@ -0,0 +1,11 @@ +# Certificate fonts + +Fonts a certificate's name can be drawn in (backend/certificates.py). The same files are served +to the browser from frontend/public/fonts so the drag-to-place view matches what is generated. + +| File | Licence | +|---|---| +| DejaVuSans.ttf, DejaVuSans-Bold.ttf, DejaVuSerif.ttf | Bitstream Vera / DejaVu licence (LICENSE_DEJAVU.txt), free to redistribute | +| IMFellEnglishSC-Regular.ttf | SIL Open Font License 1.1 (IM Fell types, Igino Marini) | + +A sender can also upload their own .ttf or .otf for one campaign; it is used only for that send. diff --git a/backend/identity.py b/backend/identity.py new file mode 100644 index 0000000000000000000000000000000000000000..17f0e9ea1b589ee4a166a81b6711e45a2d8af4dd --- /dev/null +++ b/backend/identity.py @@ -0,0 +1,106 @@ +"""Identity check (KYC), level 1: the recommended fields from docs/product/account-types.md section 6. + +Stored at identity/{uid}. A submission is "submitted" until a person on our side reviews it; nothing +here verifies anything or gates any action yet. ID numbers and uploads are not collected at this level. +""" + +from __future__ import annotations + +import re +from datetime import datetime, timezone + +from backend import accounts +from backend import firestore_client as db + +# (key, label, required) in the order they are shown. +FIELDS = { + accounts.ORGANIZATION: [ + ("legal_name", "Legal name", True), + ("trading_name", "Trading name", False), + ("registration_number", "Registration number (RC)", True), + ("country", "Country of registration", True), + ("address", "Registered address", True), + ("business_type", "Business type", True), + ("contact_name", "Contact person", True), + ("contact_role", "Their role", True), + ("contact_phone", "Their phone", True), + ("website", "Website or social page", True), + ], + accounts.INDIVIDUAL: [ + ("legal_name", "Legal name", True), + ("date_of_birth", "Date of birth", True), + ("phone", "Phone", True), + ("address", "Home or work address", True), + ("occupation", "What you send mail for", False), + ("website", "Website or social page", False), + ], +} + + +# Filled in by the map picker alongside country and address; kept if present, never required. +PHONE_KEYS = ("phone", "contact_phone") +PLACE_EXTRAS = ("state", "lga", "postal_code") + + +def _path(uid: str) -> str: + return f"identity/{uid}" + + +def overall_status(account_type: str, review: dict) -> str: + """approved: every required detail verified. needs_changes: one is rejected. Else submitted.""" + required = [k for k, _l, req in FIELDS[account_type] if req] + if any(r.get("decision") == "rejected" for r in review.values()): + return "needs_changes" + if required and all(review.get(k, {}).get("decision") == "verified" for k in required): + return "approved" + return "submitted" + + +def describe(uid: str) -> dict: + account_type = accounts.account_type_of(uid) + if not account_type: + raise accounts.AccountError("Choose an account type first") + doc = db.get_doc(_path(uid)) or {} + return { + "status": doc.get("status", "not_started"), + "values": doc.get("values", {}), + "submitted_at": doc.get("submitted_at"), + "review": doc.get("review", {}), + "fields": [{"key": k, "label": l, "required": r} for k, l, r in FIELDS[account_type]], + } + + +def status_of(uid: str) -> str: + return (db.get_doc(_path(uid)) or {}).get("status", "not_started") + + +def submit(uid: str, values: dict) -> dict: + account_type = accounts.account_type_of(uid) + if not account_type: + raise accounts.AccountError("Choose an account type first") + clean: dict[str, str] = {} + for key, label, required in FIELDS[account_type]: + value = str(values.get(key) or "").strip()[:300] + if required and not value: + raise accounts.AccountError(f"{label} is needed") + if key in PHONE_KEYS and value and not re.fullmatch(r"\+\d{1,4} \d{6,14}", value): + raise accounts.AccountError(f"{label} should be a calling code and digits only") + if value: + clean[key] = value + if clean.get("country") == "Nigeria": + rc = clean.get("registration_number") + if rc and not re.fullmatch(r"(?i)(RC|BN|IT|LP|LLP)\s?-?\s?\d{4,8}", rc): + raise accounts.AccountError("Registration number should look like RC1234567") + code = str(values.get("postal_code") or "").strip() + if code and not re.fullmatch(r"\d{6}", code): + raise accounts.AccountError("Postal code should be 6 digits") + for key in PLACE_EXTRAS: + value = str(values.get(key) or "").strip()[:300] + if value: + clean[key] = value + # A detail that did not change keeps its review; a changed or new one is looked at afresh. + old = db.get_doc(_path(uid)) or {} + review = {k: r for k, r in old.get("review", {}).items() if old.get("values", {}).get(k) == clean.get(k)} + db.set_doc(_path(uid), {"status": overall_status(account_type, review), "values": clean, "review": review, + "submitted_at": datetime.now(timezone.utc).isoformat()}) + return describe(uid) diff --git a/backend/invites.py b/backend/invites.py new file mode 100644 index 0000000000000000000000000000000000000000..38944c0f1f4aaf7230dfd7bb009ab230bff041a6 --- /dev/null +++ b/backend/invites.py @@ -0,0 +1,153 @@ +""" +Invite links: someone who can manage the team invites an email address to a role; the +person opens the link, signs in or signs up with that address, and joins. + +Firestore layout: + orgs/{org_id}/invites/{token} โ€” {email, role, invited_by, created_at, expires_at, status} + invite_tokens/{token} โ€” {org_id} (so a link can be opened without knowing the org) + +Status is "pending", "accepted" or "revoked". An invite past expires_at can't be used. +""" + +from __future__ import annotations + +import html +import re +import secrets +from datetime import datetime, timedelta, timezone + +from backend import firestore_client as db +from backend import mailboxes, mailer_client, orgs, settings +from backend.core.constants import INVITE_TTL_DAYS + +_EMAIL = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$") + + +def _now() -> datetime: + return datetime.now(timezone.utc) + + +def _path(org_id: str, token: str) -> str: + return f"orgs/{org_id}/invites/{token}" + + +def _expired(invite: dict) -> bool: + return datetime.fromisoformat(invite["expires_at"]) <= _now() + + +def create_invite(org_id: str, actor_uid: str, email: str, role: str) -> dict: + email = (email or "").strip().lower() + if not _EMAIL.match(email): + raise ValueError("Enter a valid email address") + orgs._check_grant(org_id, actor_uid, role) + if any(m.get("email", "").lower() == email for m in orgs.list_members(org_id).values()): + raise ValueError(f"{email} is already in this organisation") + for token, existing in _pending(org_id).items(): + if existing["email"] == email: + revoke_invite(org_id, actor_uid, token) + token = secrets.token_urlsafe(24) + invite = { + "email": email, + "role": role, + "invited_by": actor_uid, + "created_at": _now().isoformat(), + "expires_at": (_now() + timedelta(days=INVITE_TTL_DAYS)).isoformat(), + "status": "pending", + } + db.set_doc(_path(org_id, token), invite) + db.set_doc(f"invite_tokens/{token}", {"org_id": org_id}) + return {"token": token, **invite} + + +def _pending(org_id: str) -> dict[str, dict]: + prefix = f"orgs/{org_id}/invites/" + return { + path[len(prefix):]: data + for path, data in db.query_prefix(prefix).items() + if data["status"] == "pending" and not _expired(data) + } + + +def list_invites(org_id: str, actor_uid: str) -> list[dict]: + orgs.require_permission(org_id, actor_uid, "manage_team") + return sorted(({"token": t, **d} for t, d in _pending(org_id).items()), key=lambda d: d["created_at"]) + + +def revoke_invite(org_id: str, actor_uid: str, token: str) -> None: + orgs.require_permission(org_id, actor_uid, "manage_team") + invite = db.get_doc(_path(org_id, token)) + if invite is None: + raise orgs.NotFoundError("No such invite") + invite["status"] = "revoked" + db.set_doc(_path(org_id, token), invite) + + +def _lookup(token: str) -> tuple[str, dict]: + index = db.get_doc(f"invite_tokens/{token}") + invite = db.get_doc(_path(index["org_id"], token)) if index else None + if invite is None: + raise orgs.NotFoundError("This invite link isn't valid") + return index["org_id"], invite + + +def describe(token: str) -> dict: + """What the invite page shows before the person accepts.""" + org_id, invite = _lookup(token) + role_name = next((r["name"] for r in orgs.list_roles(org_id) if r["key"] == invite["role"]), invite["role"]) + state = invite["status"] if invite["status"] != "pending" else ("expired" if _expired(invite) else "pending") + return { + "org_id": org_id, + "org_name": orgs.get_org(org_id)["name"], + "email": invite["email"], + "role": invite["role"], + "role_name": role_name, + "status": state, + "expires_at": invite["expires_at"], + } + + +def accept(token: str, uid: str, email: str) -> str: + """Joins uid to the invite's org. The signed-in address must be the invited one. + Returns the org_id.""" + org_id, invite = _lookup(token) + if invite["status"] != "pending": + raise ValueError(f"This invite has been {invite['status']}") + if _expired(invite): + raise ValueError("This invite has expired. Ask for a new one.") + if (email or "").strip().lower() != invite["email"]: + raise orgs.PermissionError_(f"This invite is for {invite['email']}. Sign in with that address to accept it.") + orgs.join(org_id, uid, invite["role"], invite["email"]) + invite["status"] = "accepted" + invite["accepted_by"] = uid + db.set_doc(_path(org_id, token), invite) + return org_id + + +def send_invite_email(org_id: str, invite: dict, link: str, inviter: str) -> bool: + """Best effort: sends the link from the org's default (or first) verified mailbox. + Returns False when there is no mailbox to send from or the send fails; the link can + still be copied and shared by hand.""" + boxes = {cid: m for cid, m in mailboxes.list_mailboxes(org_id).items() if m.get("status") == "verified"} + if not boxes: + return False + preferred = settings.email_settings(org_id)["default_mailbox_id"] + cid = preferred if preferred in boxes else next(iter(boxes)) + org_name = orgs.get_org(org_id)["name"] + role_name = next((r["name"] for r in orgs.list_roles(org_id) if r["key"] == invite["role"]), invite["role"]) + org_html, role_html, inviter_html = (html.escape(v) for v in (org_name, role_name, inviter or "Someone")) + body = ( + f"

{inviter_html} invited you to join {org_html} on M8ion as {role_html}.

" + f'

Accept the invite

' + 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[^)]*)\) (?P"[^"]*"|NIL) (?P.+)') + + +class SentCopy: + """Files a copy of each sent message in the mailbox's Sent folder over IMAP, so it shows in + the person's own webmail (Roundcube and the like) the way mail they send by hand does. + + Best effort only: the email has already gone by the time this runs, so a missing IMAP + server, an unknown folder or a timeout is logged and the rest of the campaign carries on. + One IMAP connection is opened on the first message and reused for the whole campaign.""" + + def __init__(self, smtp_host: str, username: str, password: str, imap: dict | None = None): + self._username, self._password = username, password + self._port = 993 + host = smtp_host.strip().lower() + if imap: + # The incoming server the person gave us, with its own sign-in and port. + self._hosts = [imap["host"]] + self._username, self._password, self._port = imap["username"], imap["password"], imap["port"] + elif host in _FILES_SENT_ITSELF: + self._hosts: list[str] = [] + else: + self._hosts = [f"imap.{host[5:]}", host] if host.startswith("smtp.") else [host] + self._imap: imaplib.IMAP4_SSL | None = None + self._folder: str | None = None + self._given_up = not self._hosts + + def _connect(self) -> None: + for host in self._hosts: + try: + imap = imaplib.IMAP4_SSL(host, self._port, ssl_context=ssl.create_default_context(), timeout=10) + imap.login(self._username, self._password) + except (imaplib.IMAP4.error, OSError) as exc: + log.info("No IMAP for a Sent copy at %s: %r", host, exc) + continue + folder = _sent_folder(imap) + if folder: + self._imap, self._folder = imap, folder + return + try: + imap.logout() + except (imaplib.IMAP4.error, OSError): + pass + self._given_up = True + + def save(self, raw: bytes) -> None: + if self._given_up: + return + try: + if self._imap is None: + self._connect() + if self._imap is None: + return + self._imap.append(_quote(self._folder), "\\Seen", imaplib.Time2Internaldate(time.time()), raw) + except (imaplib.IMAP4.error, OSError) as exc: + log.warning("Could not file a Sent copy: %r", exc) + self._given_up = True + + def close(self) -> None: + if self._imap is not None: + try: + self._imap.logout() + except (imaplib.IMAP4.error, OSError): + pass + self._imap = None + + +def _quote(name: str) -> str: + return name if name.startswith('"') else '"' + name.replace("\\", "\\\\").replace('"', '\\"') + '"' + + +def _sent_folder(imap: imaplib.IMAP4) -> str | None: + """The folder the server marks as Sent (RFC 6154), else the first common Sent name.""" + status, lines = imap.list() + if status != "OK": + return None + names = [] + for line in lines or []: + text = line.decode(errors="replace") if isinstance(line, bytes) else str(line) + m = _LIST_LINE.match(text) + if not m: + continue + name = m.group("name").strip() + if "\\sent" in m.group("flags").lower(): + return name + names.append(name.strip('"')) + for wanted in _SENT_NAMES: + for name in names: + if name.lower() == wanted.lower(): + return name + return None + + +def build_message(body: str, attachments: list[Attachment], inline_images: list[InlineImage]): + """An HTML message with a plain-text copy beside it (multipart/alternative), wrapped in + multipart/related when it carries inline images and in multipart/mixed when it carries + attachments. Mail that is HTML only is treated as more likely to be spam.""" + content = MIMEText(body, "html", "utf-8") + if inline_images: + related = MIMEMultipart("related") + related.attach(content) + for img in inline_images: + part = MIMEImage(img.data, _subtype=img.subtype) + part.add_header("Content-ID", f"<{img.cid}>") + part.add_header("Content-Disposition", "inline", filename=f"{img.cid.split('@')[0]}.{img.subtype}") + related.attach(part) + content = related + alternative = MIMEMultipart("alternative") + alternative.attach(MIMEText(plain_text(body), "plain", "utf-8")) + alternative.attach(content) + content = alternative + if not attachments: + return content + mixed = MIMEMultipart("mixed") + mixed.attach(content) + for att in attachments: + maintype, _, subtype = att.content_type.partition("/") + part = MIMEBase(maintype or "application", subtype or "octet-stream") + part.set_payload(att.data) + encoders.encode_base64(part) + part.add_header("Content-Disposition", "attachment", filename=att.filename) + mixed.attach(part) + return mixed + + + +_BLOCK_END = re.compile(r"|", re.I) +_LINK = re.compile(r"]*href=[\"']([^\"']+)[\"'][^>]*>(.*?)", re.I | re.S) + + +def plain_text(body: str) -> str: + """A readable text version of an HTML email: one line per block, links as "text (url)".""" + text = re.sub(r"<(style|script|head)\b.*?", "", body, flags=re.I | re.S) + text = re.sub(r"", "", text, flags=re.S) + + def link(m: re.Match) -> str: + label = re.sub(r"<[^>]+>", "", m.group(2)).strip() + url = html.unescape(m.group(1)) + if url.startswith(("mailto:", "#")) or not label or label == url: + return label or url + return f"{label} ({url})" + + text = _LINK.sub(link, text) + text = re.sub(r"]*>", "- ", text, flags=re.I) + text = _BLOCK_END.sub("\n", text) + text = html.unescape(re.sub(r"<[^>]+>", "", text)) + lines = [" ".join(line.split()) for line in text.splitlines()] + return re.sub(r"\n{3,}", "\n\n", "\n".join(lines)).strip() + "\n" diff --git a/backend/staff.py b/backend/staff.py new file mode 100644 index 0000000000000000000000000000000000000000..c3bf8550ab2a0fc471f189db87858fa74a11f6c0 --- /dev/null +++ b/backend/staff.py @@ -0,0 +1,169 @@ +""" +M8ion's own staff: the people who run the product, as opposed to the members of a customer's +organisation. A staff member is known by a verified email address and holds one or more staff +roles; each role opens one area under /system. The director can open every area. + +Firestore layout: + staff/{email} {roles: [...], added_by, added_at} (email lower-cased, "@" and "." kept) + audit/{id} {at, by, action, target, detail} (what staff did, newest last) + +The first director comes from the SYSTEM_DIRECTOR_EMAILS environment variable (comma separated), +so there is always someone who can add the others. Nothing here reads a customer's content. +""" + +from __future__ import annotations + +import os +import uuid +from datetime import datetime, timezone + +from backend import firestore_client as db + +# key -> (label, what the area is for). Order is the order they are shown in. +AREAS: dict[str, tuple[str, str]] = { + "director": ("Director", "Everything, and who works here."), + "admin": ("Admin", "Every organisation and individual account, and their plans."), + "verification": ("Verification", "Identity checks: review each detail and approve or reject it with a reason."), + "support": ("Support", "Help people with their accounts."), + "it": ("IT", "Health of the service and its connections."), + "finance": ("Finance", "Plans, limits and what each account is owed or owes."), + "compliance": ("Compliance", "Audit trail and policy checks."), +} +DIRECTOR = "director" + + +class StaffError(Exception): + """A staff action that isn't allowed or doesn't make sense.""" + + +def _now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def _key(email: str) -> str: + return (email or "").strip().lower() + + +def _bootstrap() -> set[str]: + return {_key(e) for e in os.getenv("SYSTEM_DIRECTOR_EMAILS", "").split(",") if _key(e)} + + +def roles_of(email: str) -> list[str]: + email = _key(email) + if not email: + return [] + if email in _bootstrap(): + return [DIRECTOR] + doc = db.get_doc(f"staff/{email}") + return [r for r in (doc or {}).get("roles", []) if r in AREAS] + + +def can_open(roles: list[str], area: str) -> bool: + return DIRECTOR in roles or area in roles + + +def describe(email: str) -> dict: + roles = roles_of(email) + return { + "email": _key(email), + "is_staff": bool(roles), + "roles": roles, + "areas": [{"key": k, "label": v[0], "about": v[1], "allowed": can_open(roles, k)} for k, v in AREAS.items()], + } + + +def require(email: str, area: str) -> list[str]: + roles = roles_of(email) + if not can_open(roles, area): + raise StaffError("You do not have access to this area") + return roles + + +def list_staff() -> list[dict]: + rows = [{"email": p.split("/", 1)[1], "roles": d.get("roles", []), "added_by": d.get("added_by", ""), "added_at": d.get("added_at")} + for p, d in db.query_prefix("staff/").items()] + known = {r["email"] for r in rows} + rows += [{"email": e, "roles": [DIRECTOR], "added_by": "set up by the host", "added_at": None, "fixed": True} for e in sorted(_bootstrap() - known)] + return sorted(rows, key=lambda r: r["email"]) + + +def set_roles(actor_email: str, target_email: str, roles: list[str]) -> dict: + require(actor_email, DIRECTOR) + target = _key(target_email) + if "@" not in target or " " in target: + raise StaffError("Enter a full email address") + unknown = [r for r in roles if r not in AREAS] + if unknown: + raise StaffError(f"Unknown role {unknown[0]!r}") + if target in _bootstrap(): + raise StaffError("This director is set up by the host and cannot be changed here") + if _key(actor_email) == target: + raise StaffError("You cannot change your own roles") + roles = [r for r in AREAS if r in roles] + if not roles: + db.delete_doc(f"staff/{target}") + else: + db.set_doc(f"staff/{target}", {"roles": roles, "added_by": _key(actor_email), "added_at": _now()}) + log(actor_email, "staff.set_roles", target, ", ".join(roles) or "removed") + return {"email": target, "roles": roles} + + +def log(actor_email: str, action: str, target: str, detail: str = "") -> None: + db.set_doc(f"audit/{uuid.uuid4().hex}", {"at": _now(), "by": _key(actor_email), "action": action, "target": target, "detail": detail[:500]}) + + +def recent_audit(limit: int = 100) -> list[dict]: + rows = sorted(db.query_prefix("audit/").values(), key=lambda r: r.get("at", ""), reverse=True) + return rows[:limit] + + +# --- every account, for the admin, support and finance areas ------------------------------------- + +ALL_PLANS = ("free", "plus", "starter", "growth", "scale") + + +def list_orgs() -> list[dict]: + from backend import accounts, identity + from backend.auth import lookup_user + + rows = [] + for path, org in db.query_prefix("orgs/").items(): + org_id = path.split("/", 1)[1] + owner = org.get("owner_uid", "") + account = accounts.get_account(owner) or {} + kind = org.get("kind") or "organization" + default_plan = "free" if kind == accounts.PERSONAL_KIND else accounts.DEFAULT_ORG_PLAN + rows.append({ + "org_id": org_id, + "name": org.get("name", ""), + "kind": kind, + "plan": account.get("plan", default_plan), + "owner_email": lookup_user(owner).get("email", "") or owner, + "members": len(db.query_prefix(f"orgs/{org_id}/members/")), + "mail_limit": org.get("mail_limit"), + "identity": identity.status_of(owner), + }) + return sorted(rows, key=lambda r: r["name"].lower()) + + +def update_org(actor_email: str, org_id: str, plan: str | None, mail_limit: int | None, set_limit: bool) -> dict: + from backend import accounts + + require(actor_email, "admin") + org = db.get_doc(f"orgs/{org_id}") + if org is None: + raise StaffError("No such account") + owner = org.get("owner_uid", "") + kind = org.get("kind") or "organization" + if plan is not None: + allowed = accounts.INDIVIDUAL_PLANS if kind == accounts.PERSONAL_KIND else accounts.ORG_PLANS + if plan not in allowed: + raise StaffError(f"{plan!r} is not a plan for this kind of account (use {', '.join(allowed)})") + account = accounts.get_account(owner) or {"account_type": accounts.INDIVIDUAL if kind == accounts.PERSONAL_KIND else accounts.ORGANIZATION} + db.set_doc(f"accounts/{owner}", {**account, "plan": plan}) + if set_limit: + if mail_limit is not None and mail_limit < 0: + raise StaffError("The mail limit cannot be negative") + db.update_doc(f"orgs/{org_id}", {"mail_limit": mail_limit}) + log(actor_email, "org.update", org_id, f"plan={plan} mail_limit={mail_limit if set_limit else 'unchanged'}") + return next(r for r in list_orgs() if r["org_id"] == org_id) diff --git a/backend/static/m8ion.js b/backend/static/m8ion.js new file mode 100644 index 0000000000000000000000000000000000000000..0d06473576b10eeaab55865c424c8cf04ab71ec5 --- /dev/null +++ b/backend/static/m8ion.js @@ -0,0 +1,104 @@ +/*! M8ion Collect snippet. Adds sign-up forms to M8ion lists. + * + * + *
+ * + * + * + *
+ * + * Sends only when the visitor presses submit, and only the fields in that form. No cookies, + * no tracking, no keystroke capture. Password and file inputs are never read. + */ +(function () { + "use strict"; + + var script = document.currentScript; + var base = script && script.src ? new URL(script.src).origin : ""; + var HP = "m8ion-hp-" + Math.random().toString(36).slice(2, 8); + + var style = document.createElement("style"); + style.textContent = "." + HP + "{position:absolute!important;left:-9999px!important;width:1px;height:1px;overflow:hidden}"; + document.head.appendChild(style); + + function show(form, text, ok) { + var note = form.querySelector("[data-m8ion-message]"); + if (!note) { + note = document.createElement("p"); + note.setAttribute("data-m8ion-message", ""); + note.setAttribute("role", "status"); + form.appendChild(note); + } + note.textContent = text; + note.style.color = ok ? "" : "#b3261e"; + } + + function collect(form) { + var out = {}; + var els = form.elements; + for (var i = 0; i < els.length; i++) { + var el = els[i]; + if (!el.name || el.disabled || el.classList.contains(HP)) continue; + var type = (el.type || "").toLowerCase(); + if (type === "password" || type === "file" || type === "submit" || type === "button") continue; + if ((type === "checkbox" || type === "radio") && !el.checked) continue; + out[el.name] = type === "checkbox" ? "Yes" : el.value; + } + return out; + } + + function bind(form) { + if (form.getAttribute("data-m8ion-bound")) return; + form.setAttribute("data-m8ion-bound", "1"); + var key = form.getAttribute("data-m8ion-key"); + var shownAt = Date.now(); + + var trap = document.createElement("input"); + trap.type = "text"; + trap.name = "website"; + trap.tabIndex = -1; + trap.autocomplete = "off"; + trap.setAttribute("aria-hidden", "true"); + trap.className = HP; + form.appendChild(trap); + + form.addEventListener("submit", function (event) { + event.preventDefault(); + var button = form.querySelector("[type=submit],button:not([type])"); + if (button) button.disabled = true; + var body = JSON.stringify({ fields: collect(form), hp: trap.value, t: Date.now() - shownAt }); + // text/plain keeps this a "simple" cross-site request, so the browser sends no preflight. + fetch(base + "/collect/" + encodeURIComponent(key), { + method: "POST", + headers: { "Content-Type": "text/plain" }, + body: body, + }) + .then(function (res) { + return res.json().then(function (data) { return { ok: res.ok, data: data }; }); + }) + .then(function (r) { + if (r.ok) { + var done = form.getAttribute("data-m8ion-success") || + (r.data.pending ? "Almost done. Check your email to confirm." : "Thanks, you're signed up."); + show(form, done, true); + form.reset(); + } else { + show(form, r.data.detail || "Something went wrong. Please try again.", false); + if (button) button.disabled = false; + } + }) + .catch(function () { + show(form, "Could not reach the sign-up service. Please try again.", false); + if (button) button.disabled = false; + }); + }); + } + + function init() { + var forms = document.querySelectorAll("form[data-m8ion-key]"); + for (var i = 0; i < forms.length; i++) bind(forms[i]); + } + + if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init); + else init(); +})(); diff --git a/backend/storage.py b/backend/storage.py new file mode 100644 index 0000000000000000000000000000000000000000..661d784d1da03c6b97eeef828d1f41338b33f982 --- /dev/null +++ b/backend/storage.py @@ -0,0 +1,59 @@ +""" +Where the raw copy of an uploaded audience file is kept. An upload is never just parsed and +discarded, so the original file is stored as well. + +With SUPABASE_URL and SUPABASE_SERVICE_KEY set the file goes to a private Supabase Storage +bucket (SUPABASE_BUCKET, default "uploads"). Without them it goes to a local folder, which is +right for development and wrong for a host whose disk is wiped on restart. +""" +import os +from pathlib import Path + +import httpx + +TIMEOUT_SECONDS = 30 +CONTENT_TYPES = { + "csv": "text/csv", + "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", +} + + +class StorageError(Exception): + """The file could not be stored. The upload is refused rather than kept only in memory.""" + + +def _remote() -> tuple[str, str, str] | None: + url = os.getenv("SUPABASE_URL", "").strip().rstrip("/") + key = os.getenv("SUPABASE_SERVICE_KEY", "").strip() + if not url or not key: + return None + return url, key, os.getenv("SUPABASE_BUCKET", "uploads").strip() or "uploads" + + +def save_upload(org_id: str, database_id: str, ext: str, data: bytes) -> str: + """Stores the original file as {org_id}/{database_id}.{ext}; returns where it went.""" + name = f"{org_id}/{database_id}.{ext}" + remote = _remote() + if remote is None: + path = Path(os.getenv("UPLOADS_DIR", "uploads")) / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + return str(path) + + url, key, bucket = remote + try: + res = httpx.post( + f"{url}/storage/v1/object/{bucket}/{name}", + content=data, + headers={ + "Authorization": f"Bearer {key}", + "Content-Type": CONTENT_TYPES.get(ext.lower(), "application/octet-stream"), + "x-upsert": "true", + }, + timeout=TIMEOUT_SECONDS, + ) + except httpx.HTTPError as err: + raise StorageError(f"Could not reach file storage: {err.__class__.__name__}") from err + if res.status_code >= 300: + raise StorageError(f"File storage refused the file ({res.status_code})") + return f"{bucket}/{name}" diff --git a/backend/templating.py b/backend/templating.py new file mode 100644 index 0000000000000000000000000000000000000000..ad777b48b8d33924fc2ba04acd1eaa235a55640c --- /dev/null +++ b/backend/templating.py @@ -0,0 +1,241 @@ +""" +Per-recipient message rendering: {Field} placeholders, {Field|fallback}, list fields as bullets +or an inline "A, B and C", and {if Field has "x"}...{else}...{/if} conditional blocks. + +One engine serves both the real send and the Campaigns page's preview, so what is previewed is +what is sent. Row values are HTML-escaped when rendering HTML (a value containing "<" must not +become markup in someone's inbox); the subject is rendered as plain text and is not escaped. + +A template that cannot be rendered safely (unclosed {if}, stray {else}, a condition that does +not parse) is reported by validate_template so a send is refused up front instead of going out +half-rendered to every recipient. +""" + +from __future__ import annotations + +import html as html_lib +import re +from dataclasses import dataclass, field + +LIST_SPLIT_MIXED = re.compile(r"[;,|\n]") +_BLOCK_TOKEN = re.compile(r"\{(?:if\s+([^{}]*)|(else)|(/if))\}") +_PLACEHOLDER = re.compile(r"\{([A-Za-z0-9_][A-Za-z0-9_ ]*?)(?:\|([^{}]*))?\}") +_PARAGRAPH_TOKEN = re.compile(r"]*)?>\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[A-Za-z0-9_][A-Za-z0-9_ ]*?)\s+ + (?Pis\ not\ empty|is\ empty|is\ true|is\ false|does\ not\ contain|is\ not|is|has\ not|lacks|has|contains) + (?:\s+["โ€œโ€'](?P.*?)["โ€œโ€'])?\s*$""", + re.VERBOSE | re.IGNORECASE, +) +_NEEDS_VALUE = {"is", "is not", "has", "has not", "lacks", "contains", "does not contain"} + +_UL_STYLE = "margin:0 0 14px;padding-left:22px;" +_LI_STYLE = "margin:0 0 4px;" + + +class TemplateError(ValueError): + pass + + +@dataclass +class _Cond: + field: str + op: str + value: str + + +@dataclass +class _If: + cond: _Cond + then: list = field(default_factory=list) + other: list = field(default_factory=list) + + +def split_items(text: str, delimiter: str | None) -> list[str]: + """Splits a list-style cell into trimmed, non-empty items. delimiter "mixed" accepts any of + ; , | or a newline in the same cell (people are inconsistent), anything else is literal.""" + if not text: + return [] + if delimiter == "mixed": + parts = LIST_SPLIT_MIXED.split(text) + else: + parts = text.split(delimiter or ";") + return [p.strip() for p in parts if p.strip()] + + +def _parse_condition(raw: str) -> _Cond: + m = _CONDITION.match(html_lib.unescape(raw).strip()) + if not m: + raise TemplateError(f'Could not read the condition "{{if {raw.strip()}}}"') + op = re.sub(r"\s+", " ", m.group("op").lower()) + value = m.group("value") + if op in _NEEDS_VALUE and value is None: + raise TemplateError(f'The condition "{{if {raw.strip()}}}" needs a value in quotes') + return _Cond(m.group("field").strip(), op, (value or "").strip()) + + +def _parse(template: str) -> list: + """Template text -> tree of str and _If nodes. Raises TemplateError on unbalanced blocks.""" + root: list = [] + stack: list[tuple[_If, bool]] = [] # (node, currently_in_else) + current = root + pos = 0 + for m in _BLOCK_TOKEN.finditer(template): + if m.start() > pos: + current.append(template[pos:m.start()]) + pos = m.end() + if m.group(1) is not None: + node = _If(_parse_condition(m.group(1))) + current.append(node) + stack.append((node, False)) + current = node.then + elif m.group(2): + if not stack or stack[-1][1]: + raise TemplateError("Found {else} without a matching {if ...}") + node, _ = stack[-1] + stack[-1] = (node, True) + current = node.other + else: + if not stack: + raise TemplateError("Found {/if} without a matching {if ...}") + stack.pop() + current = stack[-1][0].other if stack and stack[-1][1] else (stack[-1][0].then if stack else root) + if stack: + raise TemplateError("An {if ...} block is missing its {/if}") + if pos < len(template): + current.append(template[pos:]) + return root + + +def _column_defs(columns: list[dict] | None) -> dict[str, dict]: + return {c["name"]: c for c in (columns or [])} + + +def _evaluate(cond: _Cond, row: dict, cols: dict[str, dict]) -> bool: + col = cols.get(cond.field) + if col is None and cols: + return False # a condition on a field the audience does not have never matches + text = str(row.get(cond.field, "") or "") + col_type = (col or {}).get("type", "text") + needle = cond.value.strip().lower() + op = cond.op + + if op == "is empty": + return text.strip() == "" + if op == "is not empty": + return text.strip() != "" + if op in ("is true", "is false"): + truthy = text.strip().lower() in {"true", "yes", "y", "1"} + return truthy if op == "is true" else not truthy + + if col_type == "tag": + items = {i.lower() for i in split_items(text, col.get("delimiter"))} + if op in ("has", "is"): + return needle in items + if op in ("lacks", "has not", "is not"): + return needle not in items + hay = text.strip().lower() + if op == "is": + return hay == needle + if op == "is not": + return hay != needle + if op in ("has", "lacks", "has not"): + # On a plain column "has" means the whole word/phrase appears, so "yes" is not + # matched by "yesterday". + found = re.search(r"(? str: + if len(items) <= 1: + return "".join(items) + return ", ".join(items[:-1]) + " and " + items[-1] + + +def _bullets(items: list[str], escape: bool) -> str: + esc = html_lib.escape if escape else (lambda s: s) + lis = "".join(f'
  • {esc(i)}
  • ' for i in items) + return f'
      {lis}
    ' + + +def _render_text(text: str, row: dict, cols: dict[str, dict], html: bool) -> str: + esc = html_lib.escape if html else (lambda s: s) + + if html: + # A list field alone in its paragraph becomes a real bullet list (replacing the paragraph). + def paragraph_list(m: re.Match) -> str: + name, mode = m.group(1).strip(), (m.group(2) or "").lower() + col = cols.get(name) + if not col or col.get("type") != "tag" or mode == "inline": + return m.group(0) + items = split_items(str(row.get(name, "") or ""), col.get("delimiter")) + return _bullets(items, True) if items else "" + + text = _PARAGRAPH_LIST.sub(paragraph_list, text) + + def placeholder(m: re.Match) -> str: + name, option = m.group(1).strip(), m.group(2) + col = cols.get(name) + raw = str(row.get(name, "") or "") + if col and col.get("type") == "tag": + items = split_items(raw, col.get("delimiter")) + if items: + if option and option.lower() == "bullets" and html: + return _bullets(items, True) + return esc(_inline_join(items)) + elif raw.strip(): + return esc(raw) + if option and option.lower() not in ("bullets", "inline"): + return option # fallback text written by the author + return "" + + return _PLACEHOLDER.sub(placeholder, text) + + +def _render(nodes: list, row: dict, cols: dict[str, dict], html: bool) -> str: + out = [] + for node in nodes: + if isinstance(node, str): + out.append(_render_text(node, row, cols, html)) + else: + branch = node.then if _evaluate(node.cond, row, cols) else node.other + out.append(_render(branch, row, cols, html)) + return "".join(out) + + +def _prepare(template: str) -> str: + # {if}/{else}/{/if} typed on their own line become their own

    ; 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 ( + '

    ' + + (f"{who}
    " if who else "") + + (f'Unsubscribe' if url else "") + + "
    " + ) + + +def suppress(org_id: str, email: str, reason: str = "unsubscribed") -> None: + email = email.strip().lower() + if db.get_doc(_path(org_id, email)) is None: + db.set_doc(_path(org_id, email), {"email": email, "reason": reason, "at": _now()}) + + +def unsubscribe_with_token(token: str) -> str: + org_id, email = parse_token(token) + suppress(org_id, email, "unsubscribed") + return email + + +def suppressed(org_id: str) -> set[str]: + return {d["email"] for d in db.query_prefix(f"orgs/{org_id}/suppressions/").values()} + + +def is_suppressed(org_id: str, email: str) -> bool: + return db.get_doc(_path(org_id, email)) is not None + + +def list_suppressed(org_id: str, actor_uid: str) -> list[dict]: + orgs.require_permission(org_id, actor_uid) + items = sorted(db.query_prefix(f"orgs/{org_id}/suppressions/").values(), key=lambda d: d.get("at", ""), reverse=True) + return [{"email": d["email"], "reason": d.get("reason", "unsubscribed"), "at": d.get("at")} for d in items] + + +def add_by_hand(org_id: str, actor_uid: str, email: str) -> None: + orgs.require_permission(org_id, actor_uid, "edit_lists") + if not _EMAIL_RE.match(email.strip()): + raise ValueError("That does not look like an email address") + suppress(org_id, email, "added by a member") + + +def remove(org_id: str, actor_uid: str, email: str) -> None: + orgs.require_permission(org_id, actor_uid, "edit_lists") + db.delete_doc(_path(org_id, email)) + + +def page(title: str, body: str) -> str: + return ( + '' + f"{html.escape(title)}" + '' + f"

    {html.escape(title)}

    {body}" + ) diff --git a/backend/unsubscribe_api.py b/backend/unsubscribe_api.py new file mode 100644 index 0000000000000000000000000000000000000000..49d6004ec1ff7582b5caa20b5ccec2dfc1c52406 --- /dev/null +++ b/backend/unsubscribe_api.py @@ -0,0 +1,39 @@ +""" +The public side of unsubscribing: the page an email's Unsubscribe link opens, and the one-click +POST that mail apps send on the reader's behalf. Nothing here needs a sign-in; the signed link +is the proof. The page asks for a click (GET never unsubscribes) so link scanners that open +every link in a message do not remove people by accident. +""" + +from __future__ import annotations + +import html + +from fastapi import APIRouter +from fastapi.responses import HTMLResponse + +from backend import unsubscribe + +router = APIRouter() + + +@router.get("/u/{token}", response_class=HTMLResponse) +def unsubscribe_page(token: str): + try: + _, email = unsubscribe.parse_token(token) + except ValueError as exc: + return HTMLResponse(unsubscribe.page("Link not valid", f"

    {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