M8ion deploy commited on
Commit
a9f88ee
·
0 Parent(s):

Deploy backend

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
.gitattributes ADDED
@@ -0,0 +1 @@
 
 
1
+ *.ttf filter=lfs diff=lfs merge=lfs -text
Dockerfile ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ # Hugging Face Spaces run the container as user 1000.
4
+ RUN useradd -m -u 1000 user
5
+ USER user
6
+ ENV HOME=/home/user PATH=/home/user/.local/bin:$PATH
7
+ WORKDIR /home/user/app
8
+
9
+ COPY --chown=user requirements.txt .
10
+ RUN pip install --no-cache-dir -r requirements.txt
11
+
12
+ COPY --chown=user backend ./backend
13
+
14
+ # The disk is wiped on restart: real data lives in Firestore and Supabase, so the local
15
+ # fallback store only needs a scratch place to exist. LOCAL_TICKER runs the send timer here.
16
+ ENV LOCAL_STORE_DB_PATH=/tmp/local_store.db LOCAL_TICKER=true UPLOADS_DIR=/tmp/uploads
17
+
18
+ EXPOSE 7860
19
+ CMD ["uvicorn", "backend.app:app", "--host", "0.0.0.0", "--port", "7860"]
README.md ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: M8ion API
3
+ emoji: 📬
4
+ colorFrom: indigo
5
+ colorTo: blue
6
+ sdk: docker
7
+ app_port: 7860
8
+ pinned: false
9
+ ---
10
+
11
+ M8ion backend. The web app is hosted separately.
backend/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from backend import config # noqa: F401 (side effect: loads .env before anything else)
backend/accounts.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Individual and organisation accounts (docs/product/account-types.md).
3
+
4
+ Every account is one or the other, and the two are kept apart on the server:
5
+
6
+ accounts/{uid} — {account_type, plan, created_at}
7
+
8
+ The type is written only from this module, by a server action: set once at registration, or
9
+ changed by `upgrade_to_organization`. There is no route that takes a type from a request body
10
+ after registration, and no client write path to this document.
11
+
12
+ An individual works inside one personal org (orgs/{id}.kind == "personal"), so the same engine
13
+ serves both. `check_org_access` is what keeps an individual out of organisation orgs and the
14
+ reverse.
15
+
16
+ Accounts that existed before this module have no document. They are treated as organisations
17
+ (each already belongs to an org) until scripts/migrate_account_types.py writes the document.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from datetime import datetime, timezone
23
+
24
+ from backend import firestore_client as db
25
+ from backend import orgs
26
+
27
+ INDIVIDUAL = "individual"
28
+ ORGANIZATION = "organization"
29
+ ACCOUNT_TYPES = (INDIVIDUAL, ORGANIZATION)
30
+
31
+ PERSONAL_KIND = "personal"
32
+
33
+ # Plan keys. Prices live in docs/product/account-types.md; nothing here bills anyone yet.
34
+ INDIVIDUAL_PLANS = ("free", "plus")
35
+ ORG_PLANS = ("starter", "growth", "scale")
36
+ DEFAULT_ORG_PLAN = "starter"
37
+
38
+
39
+ class AccountError(Exception):
40
+ """Raised for an invalid account choice or change."""
41
+
42
+
43
+ def _path(uid: str) -> str:
44
+ return f"accounts/{uid}"
45
+
46
+
47
+ def _now() -> str:
48
+ return datetime.now(timezone.utc).isoformat()
49
+
50
+
51
+ def get_account(uid: str) -> dict | None:
52
+ """The stored account document, or None when there isn't one."""
53
+ return db.get_doc(_path(uid))
54
+
55
+
56
+ def account_type_of(uid: str) -> str | None:
57
+ """The account's type. A person with no document who already belongs to an org is a
58
+ legacy organisation account; a person with neither has not chosen yet (None)."""
59
+ account = get_account(uid)
60
+ if account:
61
+ return account["account_type"]
62
+ return ORGANIZATION if orgs.list_orgs_for_user(uid) else None
63
+
64
+
65
+ def describe(uid: str) -> dict:
66
+ """What the sign-in redirect and the account gate need."""
67
+ account = get_account(uid)
68
+ account_type = account["account_type"] if account else account_type_of(uid)
69
+ default_plan = None
70
+ if account_type == ORGANIZATION:
71
+ default_plan = DEFAULT_ORG_PLAN
72
+ elif account_type == INDIVIDUAL:
73
+ default_plan = "free"
74
+ identity = db.get_doc(f"identity/{uid}") or {}
75
+ return {
76
+ "account_type": account_type,
77
+ "plan": (account or {}).get("plan", default_plan),
78
+ "legacy": account is None and account_type is not None,
79
+ "identity": identity.get("status", "not_started"),
80
+ }
81
+
82
+
83
+ def _check_plan(account_type: str, plan: str | None) -> str:
84
+ if account_type == INDIVIDUAL:
85
+ plan = plan or "free"
86
+ if plan not in INDIVIDUAL_PLANS:
87
+ raise AccountError(f"Unknown individual plan {plan!r}")
88
+ else:
89
+ plan = plan or DEFAULT_ORG_PLAN
90
+ if plan not in ORG_PLANS:
91
+ raise AccountError(f"Unknown organisation plan {plan!r}")
92
+ return plan
93
+
94
+
95
+ def register(uid: str, account_type: str, plan: str | None = None, name: str = "") -> dict:
96
+ """Sets the account type, once. An individual gets a personal org to work in; an
97
+ organisation gets the org named `name`. Legacy organisations (no document yet) may
98
+ formalise as organizations; nothing else can be re-registered."""
99
+ if account_type not in ACCOUNT_TYPES:
100
+ raise AccountError("Choose an individual or an organisation account")
101
+ existing = account_type_of(uid)
102
+ if get_account(uid) or (existing is not None and existing != account_type) or (
103
+ existing == INDIVIDUAL
104
+ ):
105
+ raise AccountError("This account type is already set and can't be changed here")
106
+ plan = _check_plan(account_type, plan)
107
+ name = (name or "").strip()
108
+
109
+ org_id = None
110
+ if account_type == INDIVIDUAL:
111
+ org_id = orgs.create_org(uid, name or "Personal", kind=PERSONAL_KIND)
112
+ elif existing is None:
113
+ if not name:
114
+ raise AccountError("Give the organisation a name")
115
+ org_id = orgs.create_org(uid, name)
116
+ db.set_doc(_path(uid), {"account_type": account_type, "plan": plan, "created_at": _now()})
117
+ return describe(uid) | {"org_id": org_id}
118
+
119
+
120
+ def ensure_organization(uid: str) -> None:
121
+ """Used when an org is created by someone with no type yet: they become an organisation."""
122
+ if get_account(uid) is None and account_type_of(uid) is None:
123
+ db.set_doc(_path(uid), {"account_type": ORGANIZATION, "plan": DEFAULT_ORG_PLAN, "created_at": _now()})
124
+
125
+
126
+ def require_organization(uid: str) -> None:
127
+ """Refuses individual accounts. A person with no type yet is allowed through; they
128
+ become an organisation by the action that follows."""
129
+ if account_type_of(uid) == INDIVIDUAL:
130
+ raise orgs.PermissionError_("This is for organisation accounts")
131
+
132
+
133
+ def can_join_org(uid: str) -> None:
134
+ """An invite can only be accepted by an organisation account (or a new person)."""
135
+ if account_type_of(uid) == INDIVIDUAL:
136
+ raise orgs.PermissionError_(
137
+ "Individual accounts can't join an organisation. Sign up with another address to accept this invite."
138
+ )
139
+
140
+
141
+ def check_org_access(uid: str, org: dict) -> None:
142
+ """Keeps the two areas apart: personal orgs for individuals, every other org for
143
+ organisation accounts. Raises PermissionError_ otherwise."""
144
+ personal = org.get("kind") == PERSONAL_KIND
145
+ account_type = account_type_of(uid)
146
+ if account_type is None:
147
+ return
148
+ if personal and account_type != INDIVIDUAL:
149
+ raise orgs.PermissionError_("This belongs to an individual account")
150
+ if not personal and account_type != ORGANIZATION:
151
+ raise orgs.PermissionError_("This belongs to an organisation account")
152
+
153
+
154
+ def is_personal(org_id: str) -> bool:
155
+ return orgs.get_org(org_id).get("kind") == PERSONAL_KIND
156
+
157
+
158
+ def upgrade_to_organization(uid: str, plan: str, org_name: str) -> dict:
159
+ """The one way an individual becomes an organisation. Server-side only: no route calls it
160
+ yet, because it needs the organisation plan and identity check first. Their personal org
161
+ (and everything in it) becomes the organisation, so nothing is lost."""
162
+ account = get_account(uid)
163
+ if not account or account["account_type"] != INDIVIDUAL:
164
+ raise AccountError("Only an individual account can be upgraded")
165
+ plan = _check_plan(ORGANIZATION, plan)
166
+ org_name = (org_name or "").strip()
167
+ if not org_name:
168
+ raise AccountError("Give the organisation a name")
169
+ personal = [oid for oid in orgs.list_orgs_for_user(uid) if is_personal(oid)]
170
+ for org_id in personal:
171
+ org = orgs.get_org(org_id)
172
+ org.pop("kind", None)
173
+ org["name"] = org_name
174
+ db.set_doc(f"orgs/{org_id}", org)
175
+ db.set_doc(_path(uid), {**account, "account_type": ORGANIZATION, "plan": plan, "upgraded_at": _now()})
176
+ return describe(uid)
backend/app.py ADDED
@@ -0,0 +1,1007 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The HTTP layer. Auth goes through backend.auth.current_uid — a real Firebase ID token
3
+ (REAL_AUTH_ENABLED=true) or the X-Dev-Uid header bypass (false, the default in tests — see
4
+ tests/conftest.py). Only exposes what the built screens actually need — grows as more
5
+ screens are built, not speculatively ahead of them.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hmac
11
+ import logging
12
+ import os
13
+ import sys
14
+ import threading
15
+ from contextlib import asynccontextmanager
16
+ from pathlib import Path
17
+
18
+ from fastapi import BackgroundTasks, Depends, FastAPI, File, Form, Header, HTTPException, UploadFile
19
+ from fastapi.middleware.cors import CORSMiddleware
20
+ from pydantic import BaseModel
21
+
22
+ 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
23
+ from backend.auth import current_email, current_uid, lookup_user
24
+ from backend import staff, verification
25
+ from backend.core.constants import PERMISSIONS
26
+ from backend.collect_api import router as collect_router
27
+ from backend.unsubscribe_api import router as unsubscribe_router
28
+
29
+
30
+ def _tick(stop: threading.Event, every: float = 1800) -> None:
31
+ while not stop.wait(every):
32
+ try:
33
+ timing.run_due()
34
+ except Exception: # one bad run must not stop the timer
35
+ logging.getLogger("m8ion").exception("Scheduled run failed")
36
+
37
+
38
+ @asynccontextmanager
39
+ async def _lifespan(app: FastAPI):
40
+ # backend/tests/conftest.py does this per-test with a throwaway file; a real running
41
+ # process needs it done once, against a persistent file, before any request lands.
42
+ local_store.init_local_store(os.getenv("LOCAL_STORE_DB_PATH", "local_store.db"))
43
+ # Locally there is no cloud timer, so a small thread plays that part. In production a
44
+ # scheduler calls POST /internal/run-due instead and nothing stays running between calls.
45
+ stop = threading.Event()
46
+ if os.getenv("LOCAL_TICKER", "true" if "pytest" not in sys.modules else "false").lower() == "true":
47
+ threading.Thread(target=_tick, args=(stop,), daemon=True).start()
48
+ yield
49
+ stop.set()
50
+
51
+
52
+ app = FastAPI(title="M8ion API", lifespan=_lifespan)
53
+
54
+ # The public sign-up endpoints (docs/blueprint/adr/0006) set their own per-key CORS headers.
55
+ app.include_router(collect_router)
56
+ app.include_router(unsubscribe_router)
57
+
58
+ app.add_middleware(
59
+ CORSMiddleware,
60
+ # Dev-only: any localhost port, since the Vite dev server's port can shift if 5173 is
61
+ # already taken (strictPort: false in vite.config.ts).
62
+ allow_origin_regex=r"http://localhost:\d+",
63
+ # The deployed web app. FRONTEND_URL can list several addresses, separated by commas.
64
+ allow_origins=[o.strip().rstrip("/") for o in os.getenv("FRONTEND_URL", "").split(",") if o.strip()],
65
+ allow_methods=["*"],
66
+ allow_headers=["*"],
67
+ )
68
+
69
+
70
+ def member_uid(org_id: str, uid: str = Depends(current_uid)) -> str:
71
+ """current_uid, for routes under /orgs/{org_id}: refuses anyone outside the org.
72
+ Finer checks (what the person's role allows) happen in each feature module."""
73
+ _map_errors(orgs.require_permission, org_id, uid)
74
+ _map_errors(accounts.check_org_access, uid, _map_errors(orgs.get_org, org_id))
75
+ return uid
76
+
77
+
78
+ def org_only_uid(org_id: str, uid: str = Depends(member_uid)) -> str:
79
+ """member_uid, for the parts an individual's personal org doesn't have: team, roles,
80
+ invites, brands, organisation details and DNS. Refused on the server, not just hidden."""
81
+ if accounts.is_personal(org_id):
82
+ raise HTTPException(status_code=403, detail="This is for organisation accounts")
83
+ return uid
84
+
85
+
86
+ def _map_errors(fn, *args, **kwargs):
87
+ try:
88
+ return fn(*args, **kwargs)
89
+ except orgs.NotFoundError as exc:
90
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
91
+ except orgs.PermissionError_ as exc:
92
+ raise HTTPException(status_code=403, detail=str(exc)) from exc
93
+ except (mailboxes.ValidationError, databases.ValidationError, accounts.AccountError, ValueError) as exc:
94
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
95
+
96
+
97
+ # --- Account type -----------------------------------------------------------
98
+
99
+ class RegisterAccountBody(BaseModel):
100
+ account_type: str
101
+ plan: str | None = None
102
+ name: str = ""
103
+
104
+
105
+ @app.get("/account")
106
+ def get_account(uid: str = Depends(current_uid)):
107
+ """Which kind of account this is, so the app can send the person to the right area."""
108
+ return accounts.describe(uid)
109
+
110
+
111
+ @app.post("/account")
112
+ def register_account(body: RegisterAccountBody, uid: str = Depends(current_uid)):
113
+ """Chooses the account type, once. After this nothing here can change it."""
114
+ return _map_errors(accounts.register, uid, body.account_type, body.plan, body.name)
115
+
116
+
117
+ class IdentityBody(BaseModel):
118
+ values: dict[str, str] = {}
119
+
120
+
121
+ @app.get("/account/identity")
122
+ def get_identity(uid: str = Depends(current_uid)):
123
+ return _map_errors(identity.describe, uid)
124
+
125
+
126
+ @app.put("/account/identity")
127
+ def submit_identity(body: IdentityBody, uid: str = Depends(current_uid)):
128
+ return _map_errors(identity.submit, uid, body.values)
129
+
130
+
131
+ # --- Orgs -------------------------------------------------------------------
132
+
133
+ class CreateOrgBody(BaseModel):
134
+ name: str
135
+
136
+
137
+ @app.post("/orgs")
138
+ def create_org(body: CreateOrgBody, uid: str = Depends(current_uid)):
139
+ _map_errors(accounts.require_organization, uid)
140
+ accounts.ensure_organization(uid)
141
+ org_id = orgs.create_org(owner_uid=uid, name=body.name)
142
+ return {"org_id": org_id, "role": "owner"}
143
+
144
+
145
+ @app.get("/orgs")
146
+ def list_orgs(uid: str = Depends(current_uid)):
147
+ return [
148
+ {"org_id": org_id, "role": role, "name": (org := orgs.get_org(org_id))["name"],
149
+ "kind": org.get("kind", "organization"),
150
+ "permissions": sorted(orgs.effective_permissions(org_id, uid))}
151
+ for org_id, role in orgs.list_orgs_for_user(uid).items()
152
+ ]
153
+
154
+
155
+ # --- Mailbox connections ------------------------------------------------------
156
+
157
+ class ConnectMailboxBody(BaseModel):
158
+ kind: str
159
+ credentials: dict
160
+
161
+
162
+ def _public_mailbox(connection_id: str, data: dict) -> dict:
163
+ """Drops encrypted_credentials — the API has no business returning that blob at all,
164
+ encrypted or not."""
165
+ return {"connection_id": connection_id, **{k: v for k, v in data.items() if k != "encrypted_credentials"}}
166
+
167
+
168
+ @app.post("/orgs/{org_id}/mailboxes")
169
+ def connect_mailbox(org_id: str, body: ConnectMailboxBody, uid: str = Depends(member_uid)):
170
+ connection_id = _map_errors(mailboxes.connect_mailbox, org_id, uid, body.kind, body.credentials)
171
+ return _public_mailbox(connection_id, mailboxes.get_mailbox(org_id, connection_id))
172
+
173
+
174
+ @app.post("/orgs/{org_id}/mailboxes/{connection_id}/verify")
175
+ def verify_mailbox(org_id: str, connection_id: str, uid: str = Depends(member_uid)):
176
+ _map_errors(orgs.require_permission, org_id, uid, "manage_mailboxes")
177
+ status = _map_errors(mailboxes.verify_mailbox, org_id, connection_id)
178
+ connection = mailboxes.get_mailbox(org_id, connection_id)
179
+ return {"connection_id": connection_id, "status": status, "status_message": connection["status_message"]}
180
+
181
+
182
+ class DismissMailboxBody(BaseModel):
183
+ dismissed: bool = True
184
+
185
+
186
+ @app.post("/orgs/{org_id}/mailboxes/{connection_id}/dismiss")
187
+ def dismiss_mailbox(org_id: str, connection_id: str, body: DismissMailboxBody, uid: str = Depends(member_uid)):
188
+ _map_errors(mailboxes.set_dismissed, org_id, uid, connection_id, body.dismissed)
189
+ return {"connection_id": connection_id, "dismissed": body.dismissed}
190
+
191
+
192
+ @app.get("/orgs/{org_id}/mailboxes")
193
+ def list_mailboxes(org_id: str, uid: str = Depends(member_uid)):
194
+ return [_public_mailbox(cid, data) for cid, data in mailboxes.list_mailboxes(org_id).items()]
195
+
196
+
197
+ @app.get("/orgs/{org_id}/mailboxes/{connection_id}")
198
+ def get_mailbox(org_id: str, connection_id: str, uid: str = Depends(member_uid)):
199
+ connection = _map_errors(mailboxes.get_mailbox, org_id, connection_id)
200
+ detail = _public_mailbox(connection_id, connection) | {
201
+ "settings": mailboxes.mailbox_settings(connection),
202
+ "sent_today": sending.sent_today(org_id, connection_id),
203
+ "next_credential_change": mailboxes.next_credential_change(connection),
204
+ }
205
+ if connection["kind"] == "smtp":
206
+ # Server details without the password, so the change form can start from them.
207
+ creds = mailboxes.get_decrypted_credentials(org_id, connection_id)
208
+ detail["smtp"] = {k: creds.get(k) for k in ("host", "port", "username")}
209
+ # The incoming side, also without its password.
210
+ detail["imap"] = {
211
+ "host": creds.get("imap_host") or "",
212
+ "port": creds.get("imap_port") or 993,
213
+ "username": creds.get("imap_username") or "",
214
+ }
215
+ return detail
216
+
217
+
218
+ class MailboxSettingsBody(BaseModel):
219
+ values: dict
220
+
221
+
222
+ @app.put("/orgs/{org_id}/mailboxes/{connection_id}/settings")
223
+ def update_mailbox_settings(org_id: str, connection_id: str, body: MailboxSettingsBody, uid: str = Depends(member_uid)):
224
+ return _map_errors(mailboxes.update_settings, org_id, uid, connection_id, body.values)
225
+
226
+
227
+ class MailboxCredentialsBody(BaseModel):
228
+ credentials: dict
229
+
230
+
231
+ @app.put("/orgs/{org_id}/mailboxes/{connection_id}/credentials")
232
+ def change_mailbox_credentials(org_id: str, connection_id: str, body: MailboxCredentialsBody, uid: str = Depends(member_uid)):
233
+ return _map_errors(mailboxes.change_credentials, org_id, uid, connection_id, body.credentials)
234
+
235
+
236
+ @app.delete("/orgs/{org_id}/mailboxes/{connection_id}")
237
+ def remove_mailbox(org_id: str, connection_id: str, uid: str = Depends(member_uid)):
238
+ _map_errors(mailboxes.remove_mailbox, org_id, uid, connection_id)
239
+ return {"ok": True}
240
+
241
+
242
+ # --- Audience databases -------------------------------------------------------
243
+
244
+ def _save_upload_copy(org_id: str, database_id: str, ext: str, file_bytes: bytes) -> None:
245
+ """Keeps the raw uploaded file, per the product requirement that an upload is never just
246
+ parsed-and-discarded. Supabase Storage when configured, a local folder otherwise."""
247
+ try:
248
+ storage.save_upload(org_id, database_id, ext, file_bytes)
249
+ except storage.StorageError as err:
250
+ raise HTTPException(503, str(err)) from err
251
+
252
+
253
+ @app.post("/orgs/{org_id}/databases")
254
+ async def create_database(
255
+ org_id: str, name: str = Form(...), file: UploadFile = File(...), uid: str = Depends(member_uid),
256
+ ):
257
+ file_bytes = await file.read()
258
+ database_id = _map_errors(
259
+ databases.create_database_from_upload,
260
+ org_id, uid, name, file_bytes, file.filename or "upload",
261
+ save_copy=lambda database_id, ext, data: _save_upload_copy(org_id, database_id, ext, data),
262
+ )
263
+ return databases.get_database(org_id, database_id) | {"database_id": database_id}
264
+
265
+
266
+ @app.get("/orgs/{org_id}/databases")
267
+ def list_databases(org_id: str, uid: str = Depends(member_uid)):
268
+ return [{"database_id": did, **data} for did, data in databases.list_databases(org_id).items()]
269
+
270
+
271
+ @app.get("/orgs/{org_id}/databases/{database_id}")
272
+ def get_database(org_id: str, database_id: str, uid: str = Depends(member_uid)):
273
+ database = _map_errors(databases.get_database, org_id, database_id)
274
+ rows = databases.list_rows(org_id, database_id)
275
+ return {"database_id": database_id, **database, "rows": rows}
276
+
277
+
278
+ class AddRowBody(BaseModel):
279
+ values: dict
280
+
281
+
282
+ @app.post("/orgs/{org_id}/databases/{database_id}/rows")
283
+ def add_row(org_id: str, database_id: str, body: AddRowBody, uid: str = Depends(member_uid)):
284
+ row_id = _map_errors(databases.add_row, org_id, uid, database_id, body.values)
285
+ return {"row_id": row_id}
286
+
287
+
288
+ class BulkSetValuesBody(BaseModel):
289
+ updates: dict[str, dict]
290
+
291
+
292
+ # Registered BEFORE /rows/{row_id} below: Starlette matches path templates in registration
293
+ # order, and {row_id} would otherwise happily capture the literal segment "batch", silently
294
+ # routing every call here into update_row instead (misrouted to the wrong handler/body model,
295
+ # not a 404 — caught via a 422 on the wrong required field, "tags", during manual testing).
296
+ @app.patch("/orgs/{org_id}/databases/{database_id}/rows/batch")
297
+ def bulk_set_values(org_id: str, database_id: str, body: BulkSetValuesBody, uid: str = Depends(member_uid)):
298
+ updated = _map_errors(databases.bulk_set_values, org_id, uid, database_id, body.updates)
299
+ return {"updated_row_ids": updated}
300
+
301
+
302
+ class UpdateRowBody(BaseModel):
303
+ tags: dict
304
+
305
+
306
+ @app.patch("/orgs/{org_id}/databases/{database_id}/rows/{row_id}")
307
+ def update_row(org_id: str, database_id: str, row_id: str, body: UpdateRowBody, uid: str = Depends(member_uid)):
308
+ _map_errors(databases.update_row, org_id, uid, database_id, row_id, body.tags)
309
+ return {"row_id": row_id}
310
+
311
+
312
+ class BulkUpdateRowsBody(BaseModel):
313
+ row_ids: list[str]
314
+ tags: dict
315
+
316
+
317
+ @app.patch("/orgs/{org_id}/databases/{database_id}/rows")
318
+ def bulk_update_rows(org_id: str, database_id: str, body: BulkUpdateRowsBody, uid: str = Depends(member_uid)):
319
+ updated = _map_errors(databases.bulk_update_rows, org_id, uid, database_id, body.row_ids, body.tags)
320
+ return {"updated_row_ids": updated}
321
+
322
+
323
+ class BulkAppendTagBody(BaseModel):
324
+ row_ids: list[str]
325
+ tag: str
326
+ tag_column: str = "Tags"
327
+
328
+
329
+ @app.post("/orgs/{org_id}/databases/{database_id}/rows/append-tag")
330
+ def bulk_append_tag(org_id: str, database_id: str, body: BulkAppendTagBody, uid: str = Depends(member_uid)):
331
+ updated = _map_errors(
332
+ databases.bulk_append_tag, org_id, uid, database_id, body.row_ids, body.tag, body.tag_column,
333
+ )
334
+ return {"updated_row_ids": updated}
335
+
336
+
337
+ class DeleteRowsBody(BaseModel):
338
+ row_ids: list[str]
339
+
340
+
341
+ @app.post("/orgs/{org_id}/databases/{database_id}/rows/delete")
342
+ def delete_rows(org_id: str, database_id: str, body: DeleteRowsBody, uid: str = Depends(member_uid)):
343
+ deleted = _map_errors(databases.delete_rows, org_id, uid, database_id, body.row_ids)
344
+ return {"deleted": deleted}
345
+
346
+
347
+ @app.get("/orgs/{org_id}/databases/{database_id}/lookups/{lookup_name}")
348
+ def get_lookup_table(org_id: str, database_id: str, lookup_name: str, uid: str = Depends(member_uid)):
349
+ return _map_errors(databases.get_lookup_table, org_id, database_id, lookup_name)
350
+
351
+
352
+ class SegmentPreviewBody(BaseModel):
353
+ conditions: list[dict]
354
+
355
+
356
+ @app.post("/orgs/{org_id}/databases/{database_id}/segment-preview")
357
+ def preview_segment(org_id: str, database_id: str, body: SegmentPreviewBody, uid: str = Depends(member_uid)):
358
+ return _map_errors(databases.preview_segment, org_id, database_id, body.conditions)
359
+
360
+
361
+ class ColumnListBody(BaseModel):
362
+ delimiter: str | None = None # None dismisses the "this looks like a list" suggestion
363
+
364
+
365
+ @app.post("/orgs/{org_id}/databases/{database_id}/columns/{column}/list")
366
+ def set_column_list(org_id: str, database_id: str, column: str, body: ColumnListBody, uid: str = Depends(member_uid)):
367
+ _map_errors(databases.set_column_list, org_id, uid, database_id, column, body.delimiter)
368
+ return {"column": column, "delimiter": body.delimiter}
369
+
370
+
371
+ class RenderPreviewBody(BaseModel):
372
+ subject: str = ""
373
+ html_body: str = ""
374
+ segment: list[dict] = []
375
+ index: int = 0
376
+ email_column: str | None = None
377
+
378
+
379
+ @app.post("/orgs/{org_id}/databases/{database_id}/render-preview")
380
+ def render_preview(org_id: str, database_id: str, body: RenderPreviewBody, uid: str = Depends(member_uid)):
381
+ return _map_errors(sending.preview_render, org_id, database_id, body.subject, body.html_body, body.segment, body.index, body.email_column)
382
+
383
+
384
+ class UpdateColumnTypeBody(BaseModel):
385
+ type: str
386
+
387
+
388
+ @app.patch("/orgs/{org_id}/databases/{database_id}/columns/{column}")
389
+ def update_column_type(org_id: str, database_id: str, column: str, body: UpdateColumnTypeBody, uid: str = Depends(member_uid)):
390
+ flagged_row_ids = _map_errors(databases.update_column_type, org_id, database_id, column, body.type)
391
+ return {"column": column, "type": body.type, "flagged_row_ids": flagged_row_ids}
392
+
393
+
394
+ class RenameColumnBody(BaseModel):
395
+ name: str
396
+
397
+
398
+ @app.get("/orgs/{org_id}/databases/{database_id}/rename-suggestions")
399
+ def column_rename_suggestions(org_id: str, database_id: str, uid: str = Depends(member_uid)):
400
+ return {"suggestions": _map_errors(databases.column_rename_suggestions, org_id, database_id)}
401
+
402
+
403
+ @app.get("/orgs/{org_id}/databases/{database_id}/type-suggestions")
404
+ def column_type_suggestions(org_id: str, database_id: str, uid: str = Depends(member_uid)):
405
+ return {"suggestions": _map_errors(databases.column_type_suggestions, org_id, database_id)}
406
+
407
+
408
+ @app.post("/orgs/{org_id}/databases/{database_id}/columns/{column}/rename")
409
+ def rename_column(org_id: str, database_id: str, column: str, body: RenameColumnBody, uid: str = Depends(member_uid)):
410
+ name = _map_errors(databases.rename_column, org_id, uid, database_id, column, body.name)
411
+ return {"column": column, "name": name}
412
+
413
+
414
+ @app.delete("/orgs/{org_id}/databases/{database_id}/columns/{column}")
415
+ def remove_column(org_id: str, database_id: str, column: str, uid: str = Depends(member_uid)):
416
+ return _map_errors(databases.remove_column, org_id, uid, database_id, column)
417
+
418
+
419
+ class RestoreColumnBody(BaseModel):
420
+ column: dict
421
+ values_by_row_id: dict[str, str]
422
+
423
+
424
+ @app.post("/orgs/{org_id}/databases/{database_id}/columns/restore")
425
+ def restore_column(org_id: str, database_id: str, body: RestoreColumnBody, uid: str = Depends(member_uid)):
426
+ _map_errors(databases.restore_column, org_id, uid, database_id, body.column, body.values_by_row_id)
427
+ return {"column": body.column["name"]}
428
+
429
+
430
+ class RenameDatabaseBody(BaseModel):
431
+ name: str
432
+
433
+
434
+ @app.patch("/orgs/{org_id}/databases/{database_id}")
435
+ def rename_database(org_id: str, database_id: str, body: RenameDatabaseBody, uid: str = Depends(member_uid)):
436
+ _map_errors(databases.rename_database, org_id, uid, database_id, body.name)
437
+ return {"database_id": database_id, "name": body.name.strip()}
438
+
439
+
440
+ class SetDisabledBody(BaseModel):
441
+ disabled: bool
442
+
443
+
444
+ @app.post("/orgs/{org_id}/databases/{database_id}/disabled")
445
+ def set_database_disabled(org_id: str, database_id: str, body: SetDisabledBody, uid: str = Depends(member_uid)):
446
+ _map_errors(databases.set_database_disabled, org_id, uid, database_id, body.disabled)
447
+ return {"database_id": database_id, "disabled": body.disabled}
448
+
449
+
450
+ @app.delete("/orgs/{org_id}/databases/{database_id}")
451
+ def delete_database(org_id: str, database_id: str, uid: str = Depends(member_uid)):
452
+ _map_errors(databases.delete_database, org_id, uid, database_id)
453
+ return {"deleted": database_id}
454
+
455
+
456
+ class DuplicateDatabaseBody(BaseModel):
457
+ new_name: str
458
+
459
+
460
+ @app.post("/orgs/{org_id}/databases/{database_id}/duplicate")
461
+ def duplicate_database(org_id: str, database_id: str, body: DuplicateDatabaseBody, uid: str = Depends(member_uid)):
462
+ new_id = _map_errors(databases.duplicate_database, org_id, uid, database_id, body.new_name)
463
+ return databases.get_database(org_id, new_id) | {"database_id": new_id}
464
+
465
+
466
+ class MergeDatabasesBody(BaseModel):
467
+ database_id_a: str
468
+ database_id_b: str
469
+ new_name: str
470
+
471
+
472
+ @app.post("/orgs/{org_id}/databases/merge")
473
+ def merge_databases(org_id: str, body: MergeDatabasesBody, uid: str = Depends(member_uid)):
474
+ database_id = _map_errors(
475
+ databases.merge_databases, org_id, uid, body.database_id_a, body.database_id_b, body.new_name,
476
+ )
477
+ return databases.get_database(org_id, database_id) | {"database_id": database_id}
478
+
479
+
480
+ # --- Customizations (saved header/footer/brand) ---------------------------------
481
+
482
+ class CustomizationBody(BaseModel):
483
+ name: str
484
+ brand_color: str = "#c0392b"
485
+ logo_url: str = ""
486
+ header_text: str = ""
487
+ footer_html: str = ""
488
+ footer_bg: str = "#f4f4f4"
489
+
490
+
491
+ @app.get("/orgs/{org_id}/customizations")
492
+ def list_customizations(org_id: str, uid: str = Depends(member_uid)):
493
+ items = _map_errors(customizations.list_customizations, org_id, uid)
494
+ return [v | {"customization_id": k} for k, v in sorted(items.items(), key=lambda kv: kv[1]["name"].lower())]
495
+
496
+
497
+ @app.post("/orgs/{org_id}/customizations")
498
+ def create_customization(org_id: str, body: CustomizationBody, uid: str = Depends(member_uid)):
499
+ cid = _map_errors(
500
+ customizations.create_customization, org_id, uid, body.name, body.brand_color,
501
+ body.logo_url, body.header_text, body.footer_html, body.footer_bg,
502
+ )
503
+ return customizations.get_customization(org_id, cid) | {"customization_id": cid}
504
+
505
+
506
+ @app.put("/orgs/{org_id}/customizations/{customization_id}")
507
+ def update_customization(org_id: str, customization_id: str, body: CustomizationBody, uid: str = Depends(member_uid)):
508
+ _map_errors(
509
+ customizations.update_customization, org_id, uid, customization_id, body.name,
510
+ body.brand_color, body.logo_url, body.header_text, body.footer_html, body.footer_bg,
511
+ )
512
+ return customizations.get_customization(org_id, customization_id) | {"customization_id": customization_id}
513
+
514
+
515
+ @app.delete("/orgs/{org_id}/customizations/{customization_id}")
516
+ def delete_customization(org_id: str, customization_id: str, uid: str = Depends(member_uid)):
517
+ _map_errors(customizations.delete_customization, org_id, uid, customization_id)
518
+ return {"deleted": customization_id}
519
+
520
+
521
+ # --- Campaigns (manual send) ---------------------------------------------------
522
+
523
+ class SendCampaignBody(BaseModel):
524
+ subject: str
525
+ html_body: str
526
+ mailbox_connection_id: str
527
+ database_id: str
528
+ segment: list[dict] | None = None
529
+ attachments: list[dict] | None = None
530
+ certificate: dict | None = None
531
+ email_column: str | None = None
532
+ mode: str | None = None
533
+ design: dict | None = None
534
+ scheduled_at: str | None = None
535
+ window: dict | None = None
536
+
537
+
538
+ @app.post("/orgs/{org_id}/campaigns/send")
539
+ def send_campaign(org_id: str, body: SendCampaignBody, background: BackgroundTasks, uid: str = Depends(member_uid)):
540
+ send_id = _map_errors(
541
+ sending.queue_campaign, org_id, uid, body.subject, body.html_body,
542
+ body.mailbox_connection_id, body.database_id, body.segment,
543
+ body.attachments, body.certificate, body.email_column, body.mode, body.design,
544
+ body.scheduled_at, body.window,
545
+ )
546
+ # The page gets its answer now; the emails go out in the background.
547
+ background.add_task(sending.process_send, org_id, send_id)
548
+ return sending.get_send(org_id, send_id) | {"send_id": send_id}
549
+
550
+
551
+ # --- Settings ---------------------------------------------------------------------
552
+
553
+ class ProfileBody(BaseModel):
554
+ display_name: str = ""
555
+ job_title: str | None = None
556
+ phone: str | None = None
557
+ about: str | None = None
558
+
559
+
560
+ class OrgNameBody(BaseModel):
561
+ name: str
562
+ profile: dict | None = None
563
+
564
+
565
+ @app.get("/orgs/{org_id}/settings")
566
+ def get_settings(org_id: str, uid: str = Depends(member_uid)):
567
+ return _map_errors(settings.get_settings, org_id, uid)
568
+
569
+
570
+ @app.put("/orgs/{org_id}/settings/profile")
571
+ def update_profile(org_id: str, body: ProfileBody, uid: str = Depends(member_uid)):
572
+ return _map_errors(settings.update_profile, org_id, uid, body.display_name, body.model_dump(exclude={"display_name"}, exclude_none=True))
573
+
574
+
575
+ @app.put("/orgs/{org_id}/settings/notifications")
576
+ def update_notifications(org_id: str, body: dict, uid: str = Depends(member_uid)):
577
+ return _map_errors(settings.update_notifications, org_id, uid, body)
578
+
579
+
580
+ @app.put("/orgs/{org_id}/settings/organisation")
581
+ def rename_org(org_id: str, body: OrgNameBody, uid: str = Depends(org_only_uid)):
582
+ return _map_errors(settings.rename_org, org_id, uid, body.name, body.profile)
583
+
584
+
585
+ @app.put("/orgs/{org_id}/settings/emails")
586
+ def update_email_settings(org_id: str, body: dict, uid: str = Depends(member_uid)):
587
+ return _map_errors(settings.update_emails, org_id, uid, body)
588
+
589
+
590
+ @app.get("/orgs/{org_id}/sends")
591
+ def list_sends(org_id: str, uid: str = Depends(member_uid)):
592
+ return _map_errors(sending.list_sends, org_id, uid)
593
+
594
+
595
+ @app.post("/orgs/{org_id}/sends/{send_id}/check-delivery")
596
+ def check_delivery(org_id: str, send_id: str, uid: str = Depends(member_uid)):
597
+ """Reads the mailbox's IMAP side now for delays, bounces and replies to this send."""
598
+ _map_errors(orgs.require_permission, org_id, uid, "send")
599
+ return _map_errors(delivery.check_send, org_id, send_id)
600
+
601
+
602
+ @app.post("/orgs/{org_id}/sends/{send_id}/{action}")
603
+ def control_send(org_id: str, send_id: str, action: str, uid: str = Depends(member_uid)):
604
+ if action not in ("pause", "resume", "cancel"):
605
+ raise HTTPException(404, "Unknown action")
606
+ return _map_errors(sending.control_send, org_id, uid, send_id, action)
607
+
608
+
609
+ @app.get("/orgs/{org_id}/suppressions")
610
+ def list_suppressions(org_id: str, uid: str = Depends(member_uid)):
611
+ return _map_errors(unsubscribe.list_suppressed, org_id, uid)
612
+
613
+
614
+ class SuppressionBody(BaseModel):
615
+ email: str
616
+
617
+
618
+ @app.post("/orgs/{org_id}/suppressions")
619
+ def add_suppression(org_id: str, body: SuppressionBody, uid: str = Depends(member_uid)):
620
+ _map_errors(unsubscribe.add_by_hand, org_id, uid, body.email)
621
+ return {"email": body.email.strip().lower()}
622
+
623
+
624
+ @app.delete("/orgs/{org_id}/suppressions")
625
+ def remove_suppression(org_id: str, email: str, uid: str = Depends(member_uid)):
626
+ _map_errors(unsubscribe.remove, org_id, uid, email)
627
+ return {"removed": email}
628
+
629
+
630
+ class AutomationBody(BaseModel):
631
+ kind: str
632
+ name: str
633
+ mailbox_connection_id: str
634
+ database_id: str
635
+ email_column: str | None = None
636
+ segment: list[dict] | None = None
637
+ start_at: str | None = None
638
+ end_at: str | None = None
639
+ steps: list[dict] | None = None
640
+ subject: str | None = None
641
+ html_body: str | None = None
642
+ every: dict | None = None
643
+ date_column: str | None = None
644
+ offset_days: int = 0
645
+ yearly: bool = False
646
+
647
+
648
+ @app.get("/orgs/{org_id}/automations")
649
+ def list_automations(org_id: str, uid: str = Depends(member_uid)):
650
+ return _map_errors(automations.list_for, org_id, uid)
651
+
652
+
653
+ @app.post("/orgs/{org_id}/automations")
654
+ def create_automation(org_id: str, body: AutomationBody, uid: str = Depends(member_uid)):
655
+ return _map_errors(automations.create, org_id, uid, body.model_dump())
656
+
657
+
658
+ @app.post("/orgs/{org_id}/automations/{automation_id}/{action}")
659
+ def control_automation(org_id: str, automation_id: str, action: str, uid: str = Depends(member_uid)):
660
+ return _map_errors(automations.control, org_id, uid, automation_id, action)
661
+
662
+
663
+ @app.delete("/orgs/{org_id}/automations/{automation_id}")
664
+ def delete_automation(org_id: str, automation_id: str, uid: str = Depends(member_uid)):
665
+ _map_errors(automations.delete, org_id, uid, automation_id)
666
+ return {"deleted": automation_id}
667
+
668
+
669
+ @app.post("/internal/run-due")
670
+ def run_due(x_cron_secret: str = Header(default="")):
671
+ """Called by the cloud scheduler (every minute or so) to carry out what is due. Closed
672
+ unless CRON_SECRET is set, and the caller must send it."""
673
+ secret = os.getenv("CRON_SECRET", "")
674
+ if not secret or not hmac.compare_digest(x_cron_secret, secret):
675
+ raise HTTPException(404, "Not found")
676
+ return timing.run_due()
677
+
678
+
679
+ @app.get("/orgs/{org_id}/sends/{send_id}")
680
+ def get_send_details(org_id: str, send_id: str, uid: str = Depends(member_uid)):
681
+ return _map_errors(sending.get_send_details, org_id, uid, send_id)
682
+
683
+
684
+ class CertificatePreviewBody(BaseModel):
685
+ database_id: str
686
+ certificate: dict
687
+ segment: list[dict] | None = None
688
+ index: int = 0
689
+ email_column: str | None = None
690
+
691
+
692
+ @app.post("/orgs/{org_id}/certificates/preview")
693
+ def preview_certificate(org_id: str, body: CertificatePreviewBody, uid: str = Depends(member_uid)):
694
+ _map_errors(orgs.require_role, org_id, uid, "operator")
695
+ return _map_errors(
696
+ sending.preview_certificate, org_id, body.database_id, body.certificate, body.segment, body.index, body.email_column,
697
+ )
698
+
699
+
700
+ # --- Presets (saved emails to start a campaign from) ----------------------------
701
+
702
+ class PresetBody(BaseModel):
703
+ name: str
704
+ subject: str = ""
705
+ mode: str
706
+ design: dict | None = None
707
+ html: str = ""
708
+
709
+
710
+ @app.get("/orgs/{org_id}/presets")
711
+ def list_presets(org_id: str, uid: str = Depends(member_uid)):
712
+ return _map_errors(presets.list_presets, org_id, uid)
713
+
714
+
715
+ @app.post("/orgs/{org_id}/presets")
716
+ def create_preset(org_id: str, body: PresetBody, uid: str = Depends(member_uid)):
717
+ preset_id = _map_errors(presets.create_preset, org_id, uid, body.name, body.subject, body.mode, body.design, body.html)
718
+ return presets.get_preset(org_id, preset_id) | {"preset_id": preset_id}
719
+
720
+
721
+ @app.put("/orgs/{org_id}/presets/{preset_id}")
722
+ def update_preset(org_id: str, preset_id: str, body: PresetBody, uid: str = Depends(member_uid)):
723
+ _map_errors(presets.update_preset, org_id, uid, preset_id, body.name, body.subject, body.mode, body.design, body.html)
724
+ return presets.get_preset(org_id, preset_id) | {"preset_id": preset_id}
725
+
726
+
727
+ @app.delete("/orgs/{org_id}/presets/{preset_id}")
728
+ def delete_preset(org_id: str, preset_id: str, uid: str = Depends(member_uid)):
729
+ _map_errors(presets.delete_preset, org_id, uid, preset_id)
730
+ return {"deleted": preset_id}
731
+
732
+
733
+ # --- Overview (the dashboard's numbers) ------------------------------------------
734
+
735
+ @app.get("/orgs/{org_id}/overview")
736
+ def get_overview(org_id: str, uid: str = Depends(member_uid)):
737
+ return _map_errors(overview.get_overview, org_id, uid)
738
+
739
+
740
+ # --- Collect (sign-up forms for a list; the public side is backend/collect_api.py) ------
741
+
742
+ class CollectKeyBody(BaseModel):
743
+ name: str
744
+ database_id: str
745
+ allowed_origins: list[str] = []
746
+ fields: list[str] | None = None
747
+ double_opt_in: bool = True
748
+ mailbox_connection_id: str | None = None
749
+ daily_cap: int = 500
750
+ welcome: dict | None = None
751
+
752
+
753
+ @app.get("/orgs/{org_id}/collect-keys")
754
+ def list_collect_keys(org_id: str, uid: str = Depends(member_uid)):
755
+ return _map_errors(collect.list_keys, org_id, uid)
756
+
757
+
758
+ @app.post("/orgs/{org_id}/collect-keys")
759
+ def create_collect_key(org_id: str, body: CollectKeyBody, uid: str = Depends(member_uid)):
760
+ return _map_errors(
761
+ collect.create_key, org_id, uid, body.name, body.database_id, body.allowed_origins,
762
+ body.fields, body.double_opt_in, body.mailbox_connection_id, body.daily_cap, body.welcome,
763
+ )
764
+
765
+
766
+ class WelcomeBody(BaseModel):
767
+ welcome: dict | None = None
768
+
769
+
770
+ @app.put("/orgs/{org_id}/collect-keys/{key_id}/welcome")
771
+ def set_collect_welcome(org_id: str, key_id: str, body: WelcomeBody, uid: str = Depends(member_uid)):
772
+ return {"welcome": _map_errors(collect.set_welcome, org_id, uid, key_id, body.welcome)}
773
+
774
+
775
+ @app.delete("/orgs/{org_id}/collect-keys/{key_id}")
776
+ def revoke_collect_key(org_id: str, key_id: str, uid: str = Depends(member_uid)):
777
+ _map_errors(collect.revoke_key, org_id, uid, key_id)
778
+ return {"revoked": key_id}
779
+
780
+
781
+ # --- Team: members, roles and invites ------------------------------------------
782
+
783
+ @app.get("/orgs/{org_id}/team")
784
+ def get_team(org_id: str, uid: str = Depends(org_only_uid)):
785
+ role = orgs.get_role(org_id, uid)
786
+ can_manage = "manage_team" in orgs.effective_permissions(org_id, uid)
787
+ members = []
788
+ for member_uid_, data in orgs.list_members(org_id).items():
789
+ known = {} if data.get("email") else lookup_user(member_uid_)
790
+ members.append({
791
+ "uid": member_uid_, "role": data["role"], "extra_roles": data.get("extra_roles", []), "added_at": data.get("added_at"),
792
+ "email": data.get("email") or known.get("email", ""), "name": known.get("name", ""),
793
+ "you": member_uid_ == uid,
794
+ })
795
+ return {
796
+ "role": role,
797
+ "can_manage": can_manage,
798
+ "permissions": PERMISSIONS,
799
+ "roles": orgs.list_roles(org_id),
800
+ "members": members,
801
+ "invites": invites.list_invites(org_id, uid) if can_manage else [],
802
+ }
803
+
804
+
805
+ class InviteBody(BaseModel):
806
+ email: str
807
+ role: str
808
+ link_base: str
809
+ inviter: str = ""
810
+
811
+
812
+ def _public_app_base(requested: str) -> str:
813
+ """The address invitees open. A link made while testing on a developer's own machine
814
+ must never reach a real inbox, so a localhost address becomes the public app."""
815
+ base = requested.strip().rstrip("/")
816
+ if os.getenv("LOCAL_MODE", "").lower() in ("1", "true", "yes"):
817
+ return base
818
+ host = base.split("://", 1)[-1].split("/", 1)[0].split(":", 1)[0].lower()
819
+ if host in ("localhost", "127.0.0.1", "[::1]", "") or host.endswith(".localhost"):
820
+ return os.getenv("PUBLIC_APP_URL", "https://m8ion.web.app").rstrip("/")
821
+ return base
822
+
823
+
824
+ @app.post("/orgs/{org_id}/invites")
825
+ def create_invite(org_id: str, body: InviteBody, uid: str = Depends(org_only_uid)):
826
+ invite = _map_errors(invites.create_invite, org_id, uid, body.email, body.role)
827
+ link = f"{_public_app_base(body.link_base)}/invite/{invite['token']}"
828
+ emailed = invites.send_invite_email(org_id, invite, link, body.inviter)
829
+ return {**invite, "link": link, "emailed": emailed}
830
+
831
+
832
+ @app.delete("/orgs/{org_id}/invites/{token}")
833
+ def revoke_invite(org_id: str, token: str, uid: str = Depends(org_only_uid)):
834
+ _map_errors(invites.revoke_invite, org_id, uid, token)
835
+ return {"ok": True}
836
+
837
+
838
+ class MemberRoleBody(BaseModel):
839
+ role: str
840
+ extra_roles: list[str] | None = None
841
+
842
+
843
+ @app.put("/orgs/{org_id}/members/{target_uid}")
844
+ def change_member_role(org_id: str, target_uid: str, body: MemberRoleBody, uid: str = Depends(org_only_uid)):
845
+ _map_errors(orgs.change_member_role, org_id, uid, target_uid, body.role)
846
+ if body.extra_roles is not None:
847
+ _map_errors(orgs.set_extra_roles, org_id, uid, target_uid, body.extra_roles)
848
+ return {"ok": True}
849
+
850
+
851
+ @app.get("/orgs/{org_id}/spaces")
852
+ def org_spaces(org_id: str, uid: str = Depends(org_only_uid)):
853
+ """Every area of the organisation with whether this member may open it."""
854
+ return orgs.spaces_for(org_id, uid)
855
+
856
+
857
+ @app.delete("/orgs/{org_id}/members/{target_uid}")
858
+ def remove_member(org_id: str, target_uid: str, uid: str = Depends(org_only_uid)):
859
+ _map_errors(orgs.remove_member, org_id, uid, target_uid)
860
+ return {"ok": True}
861
+
862
+
863
+ class RoleBody(BaseModel):
864
+ name: str = ""
865
+ permissions: list[str]
866
+
867
+
868
+ @app.post("/orgs/{org_id}/roles")
869
+ def create_role(org_id: str, body: RoleBody, uid: str = Depends(org_only_uid)):
870
+ return {"key": _map_errors(orgs.save_role, org_id, uid, None, body.name, body.permissions)}
871
+
872
+
873
+ @app.put("/orgs/{org_id}/roles/{key}")
874
+ def update_role(org_id: str, key: str, body: RoleBody, uid: str = Depends(org_only_uid)):
875
+ return {"key": _map_errors(orgs.save_role, org_id, uid, key, body.name, body.permissions)}
876
+
877
+
878
+ @app.delete("/orgs/{org_id}/roles/{key}")
879
+ def delete_role(org_id: str, key: str, uid: str = Depends(org_only_uid)):
880
+ _map_errors(orgs.delete_role, org_id, uid, key)
881
+ return {"ok": True}
882
+
883
+
884
+ @app.get("/invites/{token}")
885
+ def describe_invite(token: str, uid: str = Depends(current_uid)):
886
+ return _map_errors(invites.describe, token)
887
+
888
+
889
+ @app.post("/invites/{token}/accept")
890
+ def accept_invite(token: str, uid: str = Depends(current_uid), email: str = Depends(current_email)):
891
+ _map_errors(accounts.can_join_org, uid)
892
+ return {"org_id": _map_errors(invites.accept, token, uid, email)}
893
+
894
+
895
+ @app.post("/orgs/{org_id}/leave")
896
+ def leave_org(org_id: str, uid: str = Depends(org_only_uid)):
897
+ _map_errors(orgs.leave, org_id, uid)
898
+ return {"ok": True}
899
+
900
+
901
+ # --- Brands --------------------------------------------------------------------
902
+
903
+ @app.get("/orgs/{org_id}/brands")
904
+ def list_brands(org_id: str, uid: str = Depends(org_only_uid)):
905
+ return brands.list_brands(org_id)
906
+
907
+
908
+ @app.post("/orgs/{org_id}/brands")
909
+ def create_brand(org_id: str, body: dict, uid: str = Depends(org_only_uid)):
910
+ brand_id = _map_errors(brands.create_brand, org_id, uid, body)
911
+ return {"brand_id": brand_id, **brands.get_brand(org_id, brand_id)}
912
+
913
+
914
+ @app.put("/orgs/{org_id}/brands/{brand_id}")
915
+ def update_brand(org_id: str, brand_id: str, body: dict, uid: str = Depends(org_only_uid)):
916
+ return _map_errors(brands.update_brand, org_id, uid, brand_id, body)
917
+
918
+
919
+ @app.delete("/orgs/{org_id}/brands/{brand_id}")
920
+ def delete_brand(org_id: str, brand_id: str, uid: str = Depends(org_only_uid)):
921
+ _map_errors(brands.delete_brand, org_id, uid, brand_id)
922
+ return {"ok": True}
923
+
924
+
925
+ # --- Domain records --------------------------------------------------------------
926
+
927
+ @app.get("/orgs/{org_id}/dns/{domain}")
928
+ def check_dns(org_id: str, domain: str, uid: str = Depends(org_only_uid)):
929
+ return _map_errors(dns_check.check_domain, domain)
930
+
931
+
932
+
933
+ # --- M8ion staff (/system) -----------------------------------------------------------------------
934
+
935
+ def _staff(area: str, *others: str):
936
+ """A dependency: the signed-in, verified staff member's email, who must hold one of these roles."""
937
+ def dep(uid: str = Depends(current_uid), email: str = Depends(current_email)) -> str:
938
+ roles = staff.roles_of(email)
939
+ if not any(staff.can_open(roles, a) for a in (area, *others)):
940
+ raise HTTPException(status_code=403, detail="You do not have access to this area")
941
+ return email
942
+ return dep
943
+
944
+
945
+ def _staff_errors(fn, *args, **kwargs):
946
+ try:
947
+ return fn(*args, **kwargs)
948
+ except staff.StaffError as exc:
949
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
950
+ except verification.VerificationError as exc:
951
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
952
+
953
+
954
+ @app.get("/staff/me")
955
+ def staff_me(uid: str = Depends(current_uid), email: str = Depends(current_email)):
956
+ """Every staff area, each marked allowed or not for this person. Anyone may ask."""
957
+ return staff.describe(email)
958
+
959
+
960
+ class StaffRolesBody(BaseModel):
961
+ email: str
962
+ roles: list[str]
963
+
964
+
965
+ @app.get("/staff/team")
966
+ def staff_team(email: str = Depends(_staff("director"))):
967
+ return staff.list_staff()
968
+
969
+
970
+ @app.put("/staff/team")
971
+ def staff_set_roles(body: StaffRolesBody, email: str = Depends(_staff("director"))):
972
+ return _staff_errors(staff.set_roles, email, body.email, body.roles)
973
+
974
+
975
+ @app.get("/staff/orgs")
976
+ def staff_orgs(email: str = Depends(_staff("admin", "support", "finance"))):
977
+ return staff.list_orgs()
978
+
979
+
980
+ class StaffOrgBody(BaseModel):
981
+ plan: str | None = None
982
+ mail_limit: int | None = None
983
+
984
+
985
+ @app.put("/staff/orgs/{org_id}")
986
+ def staff_update_org(org_id: str, body: StaffOrgBody, email: str = Depends(_staff("admin"))):
987
+ return _staff_errors(staff.update_org, email, org_id, body.plan, body.mail_limit, "mail_limit" in body.model_fields_set)
988
+
989
+
990
+ @app.get("/staff/verification")
991
+ def staff_verification(email: str = Depends(_staff("verification"))):
992
+ return verification.queue()
993
+
994
+
995
+ class ReviewBody(BaseModel):
996
+ decision: str
997
+ reason: str = ""
998
+
999
+
1000
+ @app.put("/staff/verification/{target_uid}/{field}")
1001
+ def staff_review(target_uid: str, field: str, body: ReviewBody, email: str = Depends(_staff("verification"))):
1002
+ return _staff_errors(verification.review, email, target_uid, field, body.decision, body.reason)
1003
+
1004
+
1005
+ @app.get("/staff/audit")
1006
+ def staff_audit(email: str = Depends(_staff("compliance", "admin"))):
1007
+ return staff.recent_audit()
backend/auth.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Real Firebase ID token verification — decoupled from LOCAL_MODE (which only governs
3
+ storage) and from REAL_SEND_ENABLED (mail transport), same independent-flag pattern as
4
+ backend/mailer_client.py. A request either carries a real Firebase ID token
5
+ (REAL_AUTH_ENABLED=true) or, for local/dev/test convenience, an X-Dev-Uid header
6
+ (REAL_AUTH_ENABLED=false — the default in tests, see tests/conftest.py).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+
13
+ import firebase_admin
14
+ from fastapi import Header, HTTPException
15
+ from firebase_admin import auth as firebase_auth
16
+
17
+ from backend.firebase_app import get_app
18
+
19
+
20
+ def real_auth_enabled() -> bool:
21
+ return os.getenv("REAL_AUTH_ENABLED", "false").lower() == "true"
22
+
23
+
24
+ class AuthError(Exception):
25
+ pass
26
+
27
+
28
+ def verify_id_token(token: str) -> dict:
29
+ get_app()
30
+ try:
31
+ return firebase_auth.verify_id_token(token)
32
+ except firebase_admin.exceptions.FirebaseError as exc:
33
+ raise AuthError(str(exc)) from exc
34
+
35
+
36
+ def current_uid(
37
+ authorization: str | None = Header(default=None),
38
+ x_dev_uid: str = Header(default="dev-user-1", alias="X-Dev-Uid"),
39
+ ) -> str:
40
+ """FastAPI dependency — every route that needs "who is calling" uses this instead of
41
+ reading X-Dev-Uid directly, so the real/local branch lives in exactly one place."""
42
+ if not real_auth_enabled():
43
+ return x_dev_uid
44
+
45
+ if not authorization or not authorization.startswith("Bearer "):
46
+ raise HTTPException(status_code=401, detail="Missing bearer token")
47
+
48
+ token = authorization[len("Bearer "):]
49
+ try:
50
+ claims = verify_id_token(token)
51
+ except AuthError as exc:
52
+ raise HTTPException(status_code=401, detail=f"Invalid token: {exc}") from exc
53
+ # Password sign-ups must prove they own the address before touching anything real.
54
+ if not claims.get("email_verified", False):
55
+ raise HTTPException(status_code=403, detail="Email not verified")
56
+ return claims["uid"]
57
+
58
+
59
+ def current_email(
60
+ authorization: str | None = Header(default=None),
61
+ x_dev_email: str = Header(default="", alias="X-Dev-Email"),
62
+ ) -> str:
63
+ """The signed-in address (checked to be verified by current_uid). Used where an
64
+ action depends on who the person is, such as accepting an invite."""
65
+ if not real_auth_enabled():
66
+ return x_dev_email
67
+ if not authorization or not authorization.startswith("Bearer "):
68
+ raise HTTPException(status_code=401, detail="Missing bearer token")
69
+ try:
70
+ claims = verify_id_token(authorization[len("Bearer "):])
71
+ except AuthError as exc:
72
+ raise HTTPException(status_code=401, detail=f"Invalid token: {exc}") from exc
73
+ return claims.get("email", "")
74
+
75
+
76
+ def lookup_user(uid: str) -> dict:
77
+ """{email, name} for a uid, best effort; empty when unknown or running locally."""
78
+ if not real_auth_enabled():
79
+ return {}
80
+ try:
81
+ get_app()
82
+ record = firebase_auth.get_user(uid)
83
+ except Exception: # noqa: BLE001 — a missing name must not break the team list
84
+ return {}
85
+ return {"email": record.email or "", "name": record.display_name or ""}
backend/automations.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sequences, recurring sends and date-based sends.
2
+
3
+ An automation is a saved rule that makes ordinary campaigns when its time comes. Each campaign it
4
+ makes goes through `sending.queue_campaign`, so the sending window, daily limits, unsubscribe and
5
+ suppression, pause and cancel all apply exactly as they do to a campaign sent by hand.
6
+
7
+ orgs/{org}/automations/{id} the rule and its progress
8
+ active_automations/{org}_{id} the index the timer reads
9
+
10
+ Kinds
11
+ sequence a list of steps; each person gets step 1, then step 2 `delay_days` after, and so on.
12
+ People added to the list later join automatically.
13
+ recurring one message to the whole list every N days, weeks or months until it ends.
14
+ date one message sent to each person on a date taken from a column (a birthday, an expiry,
15
+ an event), a number of days before or after it, optionally every year.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import calendar
21
+ import uuid
22
+ from datetime import date, datetime, timedelta, timezone
23
+
24
+ from backend import databases, mailboxes, orgs, sending
25
+ from backend import firestore_client as db
26
+
27
+ KINDS = ("sequence", "recurring", "date")
28
+ UNITS = ("day", "week", "month")
29
+ MAX_STEPS = 10
30
+ MAX_DELAY_DAYS = 365
31
+
32
+
33
+ class AutomationError(ValueError):
34
+ """Raised for an invalid automation."""
35
+
36
+
37
+ def _path(org_id: str, automation_id: str) -> str:
38
+ return f"orgs/{org_id}/automations/{automation_id}"
39
+
40
+
41
+ def _index(org_id: str, automation_id: str) -> str:
42
+ return f"active_automations/{org_id}_{automation_id}"
43
+
44
+
45
+ def _now() -> datetime:
46
+ return datetime.now(timezone.utc)
47
+
48
+
49
+ def _parse(value: str, field: str) -> datetime:
50
+ try:
51
+ when = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
52
+ except ValueError:
53
+ raise AutomationError(f"{field} is not a date and time") from None
54
+ return when if when.tzinfo else when.replace(tzinfo=timezone.utc)
55
+
56
+
57
+ def _add_months(day: date, months: int) -> date:
58
+ index = day.month - 1 + months
59
+ year, month = day.year + index // 12, index % 12 + 1
60
+ return date(year, month, min(day.day, calendar.monthrange(year, month)[1]))
61
+
62
+
63
+ def next_after(when: datetime, every: dict) -> datetime:
64
+ n, unit = every["interval"], every["unit"]
65
+ if unit == "day":
66
+ return when + timedelta(days=n)
67
+ if unit == "week":
68
+ return when + timedelta(weeks=n)
69
+ return datetime.combine(_add_months(when.date(), n), when.timetz())
70
+
71
+
72
+ def _clean_steps(steps: list[dict] | None) -> list[dict]:
73
+ if not steps or len(steps) > MAX_STEPS:
74
+ raise AutomationError(f"A sequence has 1 to {MAX_STEPS} steps")
75
+ out = []
76
+ for i, step in enumerate(steps):
77
+ subject, body = str(step.get("subject") or "").strip(), str(step.get("html_body") or "")
78
+ delay = step.get("delay_days", 0)
79
+ if not subject or not body.strip():
80
+ raise AutomationError(f"Step {i + 1} needs a subject and a message")
81
+ if not isinstance(delay, int) or not 0 <= delay <= MAX_DELAY_DAYS:
82
+ raise AutomationError(f"Step {i + 1}: wait between 0 and {MAX_DELAY_DAYS} days")
83
+ out.append({"subject": subject, "html_body": body, "delay_days": delay})
84
+ return out
85
+
86
+
87
+ def create(org_id: str, actor_uid: str, spec: dict) -> dict:
88
+ orgs.require_permission(org_id, actor_uid, "send")
89
+ kind = spec.get("kind")
90
+ if kind not in KINDS:
91
+ raise AutomationError("Choose sequence, recurring or date")
92
+ name = str(spec.get("name") or "").strip()
93
+ if not name:
94
+ raise AutomationError("Give it a name")
95
+ mailboxes.get_mailbox(org_id, spec["mailbox_connection_id"])
96
+ database = databases.get_database(org_id, spec["database_id"])
97
+
98
+ doc = {
99
+ "kind": kind, "name": name[:120], "status": "active", "note": "",
100
+ "mailbox_connection_id": spec["mailbox_connection_id"], "database_id": spec["database_id"],
101
+ "email_column": spec.get("email_column"), "segment": spec.get("segment") or [],
102
+ "created_by": actor_uid, "created_at": _now().isoformat(), "runs": 0,
103
+ }
104
+ start = _parse(spec["start_at"], "Start") if spec.get("start_at") else _now()
105
+ if kind == "sequence":
106
+ doc |= {"steps": _clean_steps(spec.get("steps")), "start_at": start.isoformat(), "enrolled": {}}
107
+ else:
108
+ subject, body = str(spec.get("subject") or "").strip(), str(spec.get("html_body") or "")
109
+ if not subject or not body.strip():
110
+ raise AutomationError("It needs a subject and a message")
111
+ doc |= {"subject": subject, "html_body": body}
112
+ if kind == "recurring":
113
+ every = spec.get("every") or {}
114
+ if every.get("unit") not in UNITS or not isinstance(every.get("interval"), int) or not 1 <= every["interval"] <= 365:
115
+ raise AutomationError("Choose how often: every N days, weeks or months")
116
+ end = _parse(spec["end_at"], "End").isoformat() if spec.get("end_at") else None
117
+ doc |= {"every": {"unit": every["unit"], "interval": every["interval"]}, "next_at": start.isoformat(), "end_at": end}
118
+ else:
119
+ column = spec.get("date_column")
120
+ if column not in [c["name"] for c in database["columns"]]:
121
+ raise AutomationError("Choose the column that holds the date")
122
+ offset = spec.get("offset_days", 0)
123
+ if not isinstance(offset, int) or abs(offset) > MAX_DELAY_DAYS:
124
+ raise AutomationError(f"Offset must be within {MAX_DELAY_DAYS} days")
125
+ doc |= {"date_column": column, "offset_days": offset, "yearly": bool(spec.get("yearly")), "fired": {}}
126
+
127
+ automation_id = uuid.uuid4().hex
128
+ db.set_doc(_path(org_id, automation_id), doc)
129
+ db.set_doc(_index(org_id, automation_id), {"org_id": org_id, "automation_id": automation_id})
130
+ return get(org_id, actor_uid, automation_id)
131
+
132
+
133
+ def get(org_id: str, actor_uid: str, automation_id: str) -> dict:
134
+ orgs.require_permission(org_id, actor_uid, "send")
135
+ doc = db.get_doc(_path(org_id, automation_id))
136
+ if not doc:
137
+ raise orgs.NotFoundError(f"Automation {automation_id!r} not found")
138
+ return _public(automation_id, doc)
139
+
140
+
141
+ def _public(automation_id: str, doc: dict) -> dict:
142
+ out = {k: v for k, v in doc.items() if k not in ("enrolled", "fired")}
143
+ out["automation_id"] = automation_id
144
+ if doc["kind"] == "sequence":
145
+ steps = len(doc["steps"])
146
+ out["people"] = len(doc.get("enrolled", {}))
147
+ out["finished"] = sum(1 for e in doc.get("enrolled", {}).values() if e["step"] >= steps)
148
+ return out
149
+
150
+
151
+ def list_for(org_id: str, actor_uid: str) -> list[dict]:
152
+ orgs.require_permission(org_id, actor_uid, "send")
153
+ docs = db.query_prefix(f"orgs/{org_id}/automations/")
154
+ rows = [_public(path.rsplit("/", 1)[-1], d) for path, d in docs.items()]
155
+ return sorted(rows, key=lambda a: a["created_at"], reverse=True)
156
+
157
+
158
+ def control(org_id: str, actor_uid: str, automation_id: str, action: str) -> dict:
159
+ orgs.require_permission(org_id, actor_uid, "send")
160
+ doc = db.get_doc(_path(org_id, automation_id))
161
+ if not doc:
162
+ raise orgs.NotFoundError(f"Automation {automation_id!r} not found")
163
+ status = doc["status"]
164
+ if action == "pause" and status == "active":
165
+ new = "paused"
166
+ elif action == "resume" and status == "paused":
167
+ new = "active"
168
+ elif action == "stop" and status in ("active", "paused"):
169
+ new = "stopped"
170
+ else:
171
+ raise AutomationError(f"This is {status}, so it cannot be {action}d")
172
+ db.update_doc(_path(org_id, automation_id), {"status": new, "note": ""})
173
+ if new == "active":
174
+ db.set_doc(_index(org_id, automation_id), {"org_id": org_id, "automation_id": automation_id})
175
+ else:
176
+ db.delete_doc(_index(org_id, automation_id))
177
+ return get(org_id, actor_uid, automation_id)
178
+
179
+
180
+ def delete(org_id: str, actor_uid: str, automation_id: str) -> None:
181
+ orgs.require_permission(org_id, actor_uid, "send")
182
+ db.delete_doc(_path(org_id, automation_id))
183
+ db.delete_doc(_index(org_id, automation_id))
184
+
185
+
186
+ # --- The timer ---------------------------------------------------------------
187
+
188
+ def _queue(org_id: str, doc: dict, subject: str, html_body: str, row_ids: list[str]) -> None:
189
+ sending.queue_campaign(
190
+ org_id, doc["created_by"], subject, html_body, doc["mailbox_connection_id"], doc["database_id"],
191
+ doc.get("segment"), email_column=doc.get("email_column"), only_row_ids=row_ids, automated=True,
192
+ )
193
+
194
+
195
+ def _rows(org_id: str, doc: dict) -> list[dict]:
196
+ database = databases.get_database(org_id, doc["database_id"])
197
+ return sending._recipient_rows(org_id, doc["database_id"], database, doc.get("segment"), doc.get("email_column"))
198
+
199
+
200
+ def _row_date(value) -> date | None:
201
+ text = str(value or "").strip()
202
+ for fmt, size in (("%Y-%m-%d", 10), ("%d/%m/%Y", 10)):
203
+ try:
204
+ return datetime.strptime(text[:size], fmt).date()
205
+ except ValueError:
206
+ continue
207
+ return None
208
+
209
+
210
+ def _step_sequence(org_id: str, doc: dict, now: datetime) -> bool:
211
+ if _parse(doc["start_at"], "Start") > now:
212
+ return False
213
+ enrolled = doc["enrolled"]
214
+ rows = _rows(org_id, doc)
215
+ for row in rows: # anyone new on the list joins at step one
216
+ enrolled.setdefault(row["row_id"], {"step": 0, "next_at": (now + timedelta(days=doc["steps"][0]["delay_days"])).isoformat()})
217
+ live = {r["row_id"] for r in rows}
218
+ due: dict[int, list[str]] = {}
219
+ for row_id, state in enrolled.items():
220
+ if row_id in live and state["step"] < len(doc["steps"]) and _parse(state["next_at"], "") <= now:
221
+ due.setdefault(state["step"], []).append(row_id)
222
+ for step_no, row_ids in sorted(due.items()):
223
+ step = doc["steps"][step_no]
224
+ _queue(org_id, doc, step["subject"], step["html_body"], row_ids)
225
+ following = doc["steps"][step_no + 1]["delay_days"] if step_no + 1 < len(doc["steps"]) else 0
226
+ for row_id in row_ids:
227
+ enrolled[row_id] = {"step": step_no + 1, "next_at": (now + timedelta(days=following)).isoformat()}
228
+ doc["runs"] += 1
229
+ return True # enrolling new people changes the record even when nothing is due
230
+
231
+
232
+ def _step_recurring(org_id: str, doc: dict, now: datetime) -> bool:
233
+ if _parse(doc["next_at"], "") > now:
234
+ return False
235
+ end = _parse(doc["end_at"], "") if doc.get("end_at") else None
236
+ if end and now > end:
237
+ doc["status"] = "done"
238
+ return True
239
+ _queue(org_id, doc, doc["subject"], doc["html_body"], [r["row_id"] for r in _rows(org_id, doc)])
240
+ doc["runs"] += 1
241
+ nxt = next_after(_parse(doc["next_at"], ""), doc["every"])
242
+ while nxt <= now: # missed periods are skipped, not sent in a burst
243
+ nxt = next_after(nxt, doc["every"])
244
+ doc["next_at"] = nxt.isoformat()
245
+ return True
246
+
247
+
248
+ def _step_date(org_id: str, doc: dict, now: datetime) -> bool:
249
+ today = now.date()
250
+ due = []
251
+ for row in _rows(org_id, doc):
252
+ day = _row_date(row.get(doc["date_column"]))
253
+ if day is None:
254
+ continue
255
+ if doc["yearly"]:
256
+ try:
257
+ day = day.replace(year=today.year)
258
+ except ValueError: # 29 February in a year without one
259
+ day = date(today.year, 3, 1)
260
+ target = day + timedelta(days=doc["offset_days"])
261
+ key = str(target.year if doc["yearly"] else target)
262
+ if target == today and doc["fired"].get(row["row_id"]) != key:
263
+ due.append((row["row_id"], key))
264
+ if not due:
265
+ return False
266
+ _queue(org_id, doc, doc["subject"], doc["html_body"], [r for r, _ in due])
267
+ for row_id, key in due:
268
+ doc["fired"][row_id] = key
269
+ doc["runs"] += 1
270
+ return True
271
+
272
+
273
+ _STEPS = {"sequence": _step_sequence, "recurring": _step_recurring, "date": _step_date}
274
+
275
+
276
+ def run_one(org_id: str, automation_id: str, now: datetime | None = None) -> None:
277
+ now = now or _now()
278
+ doc = db.get_doc(_path(org_id, automation_id))
279
+ if not doc:
280
+ raise orgs.NotFoundError(automation_id)
281
+ if doc["status"] != "active":
282
+ db.delete_doc(_index(org_id, automation_id))
283
+ return
284
+ try:
285
+ changed = _STEPS[doc["kind"]](org_id, doc, now)
286
+ except (ValueError, orgs.NotFoundError) as err: # e.g. the mailbox needs attention: wait for a person
287
+ db.update_doc(_path(org_id, automation_id), {"status": "paused", "note": f"Paused: {err}"})
288
+ db.delete_doc(_index(org_id, automation_id))
289
+ return
290
+ if changed:
291
+ db.set_doc(_path(org_id, automation_id), doc)
292
+ if doc["status"] != "active":
293
+ db.delete_doc(_index(org_id, automation_id))
294
+
295
+
296
+ def run_due(now: datetime | None = None) -> dict:
297
+ checked = 0
298
+ for entry in list(db.query_prefix("active_automations/").values()):
299
+ try:
300
+ run_one(entry["org_id"], entry["automation_id"], now)
301
+ except orgs.NotFoundError:
302
+ db.delete_doc(_index(entry["org_id"], entry["automation_id"]))
303
+ checked += 1
304
+ return {"checked": checked}
backend/brands.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Brands: the businesses one organisation sends for. Each has its own name, logo, domain,
3
+ sender name and replies address, and owns some of the org's mailboxes. Lists, saved
4
+ emails and the team stay shared across brands.
5
+
6
+ A mailbox belongs to at most one brand. When a campaign goes out, the brand that owns
7
+ the chosen mailbox supplies the sender details the mailbox doesn't set itself (mailbox,
8
+ then brand, then organisation defaults).
9
+
10
+ Firestore layout:
11
+ orgs/{org_id}/brands/{brand_id} — {name, logo_url, domain, from_name, reply_to, mailbox_ids, created_at}
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import re
17
+ import uuid
18
+ from datetime import datetime, timezone
19
+
20
+ from backend import firestore_client as db
21
+ from backend import mailboxes, orgs
22
+
23
+ _EMAIL = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
24
+ _DOMAIN = re.compile(r"^(?=.{3,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$")
25
+ FIELDS = ("name", "logo_url", "domain", "from_name", "reply_to", "mailbox_ids")
26
+
27
+
28
+ def _path(org_id: str, brand_id: str) -> str:
29
+ return f"orgs/{org_id}/brands/{brand_id}"
30
+
31
+
32
+ def list_brands(org_id: str) -> list[dict]:
33
+ prefix = f"orgs/{org_id}/brands/"
34
+ items = [{"brand_id": path[len(prefix):], **data} for path, data in db.query_prefix(prefix).items()]
35
+ return sorted(items, key=lambda b: b["name"].lower())
36
+
37
+
38
+ def get_brand(org_id: str, brand_id: str) -> dict:
39
+ doc = db.get_doc(_path(org_id, brand_id))
40
+ if doc is None:
41
+ raise orgs.NotFoundError(f"No brand {brand_id!r}")
42
+ return doc
43
+
44
+
45
+ def brand_for_mailbox(org_id: str, connection_id: str) -> dict | None:
46
+ return next((b for b in list_brands(org_id) if connection_id in b.get("mailbox_ids", [])), None)
47
+
48
+
49
+ def _clean(org_id: str, values: dict, brand_id: str | None) -> dict:
50
+ unknown = set(values) - set(FIELDS)
51
+ if unknown:
52
+ raise ValueError(f"Unknown brand field: {', '.join(sorted(unknown))}")
53
+ out = {k: values[k] for k in FIELDS if k in values}
54
+ for key in ("name", "from_name"):
55
+ if key in out:
56
+ out[key] = " ".join(str(out[key] or "").split()).replace('"', "")
57
+ if len(out[key]) > 80:
58
+ raise ValueError("Keep names to 80 characters or fewer")
59
+ if "name" in out:
60
+ if not out["name"]:
61
+ raise ValueError("Give the brand a name")
62
+ if any(b["name"].lower() == out["name"].lower() and b["brand_id"] != brand_id for b in list_brands(org_id)):
63
+ raise ValueError(f"There is already a brand called {out['name']!r}")
64
+ if "reply_to" in out:
65
+ out["reply_to"] = str(out["reply_to"] or "").strip()
66
+ if out["reply_to"] and not _EMAIL.match(out["reply_to"]):
67
+ raise ValueError("The replies address doesn't look like an email address")
68
+ if "domain" in out:
69
+ domain = str(out["domain"] or "").strip().lower().removeprefix("https://").removeprefix("http://").removeprefix("www.").rstrip("/")
70
+ if domain and not _DOMAIN.match(domain):
71
+ raise ValueError("Enter a domain like yourbrand.com")
72
+ out["domain"] = domain
73
+ if "logo_url" in out:
74
+ logo = str(out["logo_url"] or "").strip()
75
+ if logo and not logo.startswith("https://"):
76
+ raise ValueError("The logo address must start with https://")
77
+ out["logo_url"] = logo
78
+ if "mailbox_ids" in out:
79
+ ids = list(dict.fromkeys(str(i) for i in out["mailbox_ids"] or []))
80
+ for cid in ids:
81
+ mailboxes.get_mailbox(org_id, cid) # NotFoundError for anything not in this org
82
+ out["mailbox_ids"] = ids
83
+ return out
84
+
85
+
86
+ def _take_mailboxes(org_id: str, brand_id: str, ids: list[str]) -> None:
87
+ """A mailbox moves to this brand: it leaves whichever brand had it."""
88
+ for other in list_brands(org_id):
89
+ if other["brand_id"] != brand_id and set(other.get("mailbox_ids", [])) & set(ids):
90
+ db.update_doc(_path(org_id, other["brand_id"]), {"mailbox_ids": [i for i in other["mailbox_ids"] if i not in ids]})
91
+
92
+
93
+ def create_brand(org_id: str, actor_uid: str, values: dict) -> str:
94
+ orgs.require_permission(org_id, actor_uid, "manage_settings")
95
+ clean = _clean(org_id, {"name": values.get("name", "")} | values, None)
96
+ brand_id = uuid.uuid4().hex
97
+ doc = {"logo_url": "", "domain": "", "from_name": "", "reply_to": "", "mailbox_ids": []} | clean
98
+ _take_mailboxes(org_id, brand_id, doc["mailbox_ids"])
99
+ db.set_doc(_path(org_id, brand_id), doc | {"created_at": datetime.now(timezone.utc).isoformat()})
100
+ return brand_id
101
+
102
+
103
+ def update_brand(org_id: str, actor_uid: str, brand_id: str, values: dict) -> dict:
104
+ orgs.require_permission(org_id, actor_uid, "manage_settings")
105
+ get_brand(org_id, brand_id)
106
+ clean = _clean(org_id, values, brand_id)
107
+ if "mailbox_ids" in clean:
108
+ _take_mailboxes(org_id, brand_id, clean["mailbox_ids"])
109
+ db.update_doc(_path(org_id, brand_id), clean)
110
+ return {"brand_id": brand_id, **get_brand(org_id, brand_id)}
111
+
112
+
113
+ def delete_brand(org_id: str, actor_uid: str, brand_id: str) -> None:
114
+ """Its mailboxes stay connected and go back to using the organisation's defaults."""
115
+ orgs.require_permission(org_id, actor_uid, "manage_settings")
116
+ get_brand(org_id, brand_id)
117
+ db.delete_doc(_path(org_id, brand_id))
backend/certificates.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Per-person certificates: one uploaded image with each recipient's name (or any {Column} text)
3
+ drawn onto it, attached to that recipient's copy of a campaign.
4
+
5
+ The sender places the text by dragging it on the image in the browser; the position arrives
6
+ here as fractions of the image's width and height, so it means the same thing at any display
7
+ size. The font size is in the image's own pixels. Fonts are the bundled ones in backend/fonts
8
+ (the browser loads the same files) or one the sender uploads for this send.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import base64
14
+ import binascii
15
+ import re
16
+ from dataclasses import dataclass
17
+ from io import BytesIO
18
+ from pathlib import Path
19
+
20
+ from PIL import Image, ImageDraw, ImageFont, UnidentifiedImageError
21
+
22
+ from backend import templating
23
+ from backend.email_parts import Attachment, safe_filename
24
+
25
+ FONTS_DIR = Path(__file__).parent / "fonts"
26
+ BUILTIN_FONTS = {
27
+ "sans": "DejaVuSans.ttf",
28
+ "sans-bold": "DejaVuSans-Bold.ttf",
29
+ "serif": "DejaVuSerif.ttf",
30
+ "classic": "IMFellEnglishSC-Regular.ttf",
31
+ }
32
+ MAX_IMAGE_BYTES = 10 * 1024 * 1024
33
+ MAX_FONT_BYTES = 5 * 1024 * 1024
34
+ MAX_SIDE_PX = 8000
35
+ _COLOR_RE = re.compile(r"^#[0-9a-fA-F]{6}$")
36
+
37
+
38
+ @dataclass
39
+ class CertificateSpec:
40
+ image: Image.Image
41
+ text: str
42
+ filename: str
43
+ x: float
44
+ y: float
45
+ font_size: int
46
+ color: tuple[int, int, int]
47
+ font_bytes: bytes
48
+ letter_spacing: int
49
+ output: str # "png" or "pdf"
50
+
51
+
52
+ def _b64(value: str | None, what: str) -> bytes:
53
+ try:
54
+ return base64.b64decode(value or "", validate=True)
55
+ except (binascii.Error, ValueError) as exc:
56
+ raise ValueError(f"The {what} could not be read") from exc
57
+
58
+
59
+ def parse_spec(raw: dict) -> CertificateSpec:
60
+ """Validates the request's certificate settings. Raises ValueError with a message the
61
+ sender can act on."""
62
+ image_bytes = _b64(raw.get("image_b64"), "certificate image")
63
+ if not image_bytes:
64
+ raise ValueError("Choose a certificate image")
65
+ if len(image_bytes) > MAX_IMAGE_BYTES:
66
+ raise ValueError("The certificate image is larger than 10 MB")
67
+ try:
68
+ image = Image.open(BytesIO(image_bytes))
69
+ image.load()
70
+ except (UnidentifiedImageError, OSError) as exc:
71
+ raise ValueError("The certificate image must be a PNG or JPEG") from exc
72
+ if max(image.size) > MAX_SIDE_PX:
73
+ raise ValueError(f"The certificate image is wider or taller than {MAX_SIDE_PX} pixels")
74
+
75
+ text = str(raw.get("text") or "").strip()
76
+ if not text:
77
+ raise ValueError("Say what to write on the certificate, for example {Name}")
78
+ if len(text) > 300:
79
+ raise ValueError("The certificate text is too long")
80
+
81
+ try:
82
+ x, y = float(raw.get("x", 0.5)), float(raw.get("y", 0.5))
83
+ font_size = int(raw.get("font_size", 64))
84
+ letter_spacing = int(raw.get("letter_spacing", 0))
85
+ except (TypeError, ValueError) as exc:
86
+ raise ValueError("The certificate text position is not valid") from exc
87
+ if not (0 <= x <= 1 and 0 <= y <= 1):
88
+ raise ValueError("Place the text inside the image")
89
+ if not 6 <= font_size <= 1000:
90
+ raise ValueError("Pick a text size between 6 and 1000")
91
+ letter_spacing = max(-50, min(200, letter_spacing))
92
+
93
+ color = str(raw.get("color") or "#000000")
94
+ if not _COLOR_RE.match(color):
95
+ raise ValueError("The text colour must look like #1a2b3c")
96
+
97
+ font_key = str(raw.get("font") or "sans")
98
+ if font_key == "custom":
99
+ font_bytes = _b64(raw.get("font_b64"), "font file")
100
+ if not font_bytes or len(font_bytes) > MAX_FONT_BYTES:
101
+ raise ValueError("Upload a .ttf or .otf font under 5 MB")
102
+ elif font_key in BUILTIN_FONTS:
103
+ font_bytes = (FONTS_DIR / BUILTIN_FONTS[font_key]).read_bytes()
104
+ else:
105
+ raise ValueError("Pick one of the listed fonts")
106
+ try:
107
+ ImageFont.truetype(BytesIO(font_bytes), 12)
108
+ except OSError as exc:
109
+ raise ValueError("That font file could not be used") from exc
110
+
111
+ output = "pdf" if raw.get("output") == "pdf" else "png"
112
+ filename = str(raw.get("filename") or "Certificate for {Name}").strip() or "Certificate"
113
+ return CertificateSpec(
114
+ image=image, text=text, filename=filename, x=x, y=y, font_size=font_size,
115
+ color=tuple(int(color[i:i + 2], 16) for i in (1, 3, 5)), font_bytes=font_bytes,
116
+ letter_spacing=letter_spacing, output=output,
117
+ )
118
+
119
+
120
+ def render(spec: CertificateSpec, text: str) -> bytes:
121
+ """Draws `text` centred on (x, y) and returns the finished file's bytes."""
122
+ img = spec.image.convert("RGBA")
123
+ draw = ImageDraw.Draw(img)
124
+ font = ImageFont.truetype(BytesIO(spec.font_bytes), spec.font_size)
125
+ cx, cy = spec.x * img.width, spec.y * img.height
126
+ if spec.letter_spacing == 0:
127
+ draw.text((cx, cy), text, font=font, fill=spec.color, anchor="mm")
128
+ else:
129
+ widths = [font.getlength(ch) for ch in text]
130
+ total = sum(widths) + spec.letter_spacing * max(0, len(text) - 1)
131
+ x = cx - total / 2
132
+ for ch, w in zip(text, widths):
133
+ draw.text((x, cy), ch, font=font, fill=spec.color, anchor="lm")
134
+ x += w + spec.letter_spacing
135
+
136
+ buf = BytesIO()
137
+ if spec.output == "pdf":
138
+ img.convert("RGB").save(buf, "PDF", resolution=150)
139
+ else:
140
+ img.save(buf, "PNG", optimize=True)
141
+ return buf.getvalue()
142
+
143
+
144
+ def text_for(spec: CertificateSpec, row: dict, columns: list[dict] | None) -> str:
145
+ return templating.render(spec.text, row, columns, html=False).strip()
146
+
147
+
148
+ def attachment_for(spec: CertificateSpec, row: dict, columns: list[dict] | None) -> Attachment:
149
+ text = text_for(spec, row, columns)
150
+ name = safe_filename(templating.render(spec.filename, row, columns, html=False), "Certificate")
151
+ ext = spec.output
152
+ return Attachment(
153
+ filename=f"{name}.{ext}",
154
+ content_type="application/pdf" if ext == "pdf" else "image/png",
155
+ data=render(spec, text),
156
+ )
157
+
158
+
159
+ def preview_png(spec: CertificateSpec, text: str, max_width: int = 1400) -> bytes:
160
+ """A PNG of the certificate for the composer, scaled down so it loads quickly."""
161
+ png_spec = CertificateSpec(**{**spec.__dict__, "output": "png"})
162
+ img = Image.open(BytesIO(render(png_spec, text)))
163
+ if img.width > max_width:
164
+ img = img.resize((max_width, round(img.height * max_width / img.width)), Image.LANCZOS)
165
+ buf = BytesIO()
166
+ img.save(buf, "PNG", optimize=True)
167
+ return buf.getvalue()
backend/collect.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Public collection ("Collect") — lets people on a user's own website land in one of that user's
3
+ databases through a public key + a snippet. See docs/blueprint/adr/0006.
4
+
5
+ The public key is NOT a secret and can do almost nothing: create a *pending* sign-up. Its rules
6
+ live here, server-side (allowed origins, allowed columns, daily cap, double opt-in). A sign-up
7
+ only becomes a database row once the person confirms from their inbox, and every check that
8
+ could stop a bot runs BEFORE a confirmation email is sent — that email goes out from the user's
9
+ own mailbox, so one sent to a stranger costs the user's sender reputation.
10
+
11
+ This module is the only thing the public router (backend/collect_api.py) may call. It never
12
+ reads rows out, never exposes credentials, and never sends a campaign.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import hashlib
18
+ import html
19
+ import json
20
+ import logging
21
+ import os
22
+ import secrets
23
+ import uuid
24
+ from datetime import datetime, timedelta, timezone
25
+
26
+ from backend import databases, mailboxes, mailer_client, orgs, rate_limiter
27
+ from backend import firestore_client as db
28
+ from backend.core import constants as C
29
+ from backend.crypto_utils import decrypt, encrypt
30
+ from backend.mock_mailer import AuthError, ConnectionFailure
31
+
32
+
33
+ class CollectError(Exception):
34
+ """A hard rejection the public caller is allowed to see. `status` is the HTTP code."""
35
+
36
+ def __init__(self, status: int, message: str):
37
+ self.status = status
38
+ super().__init__(message)
39
+
40
+
41
+ def _now() -> datetime:
42
+ return datetime.now(timezone.utc)
43
+
44
+
45
+ def _key_path(org_id: str, key_id: str) -> str:
46
+ return f"orgs/{org_id}/collect_keys/{key_id}"
47
+
48
+
49
+ def _index_path(public_key: str) -> str:
50
+ return f"collect_index/{public_key}"
51
+
52
+
53
+ def _pending_path(token: str) -> str:
54
+ return f"collect_pending/{token}"
55
+
56
+
57
+ def _consent_path(org_id: str, row_id: str) -> str:
58
+ return f"orgs/{org_id}/consents/{row_id}"
59
+
60
+
61
+ def _blocked(field: str) -> bool:
62
+ lowered = field.lower()
63
+ return any(word in lowered for word in C.COLLECT_BLOCKED_FIELD_WORDS)
64
+
65
+
66
+ def _normalize_origin(origin: str) -> str:
67
+ origin = origin.strip().rstrip("/").lower()
68
+ if not (origin.startswith("http://") or origin.startswith("https://")) or "/" in origin.split("://", 1)[1]:
69
+ raise ValueError(f"{origin!r} is not a site address. Use something like https://example.com")
70
+ return origin
71
+
72
+
73
+ def _email_column(database: dict) -> str | None:
74
+ for col in database["columns"]:
75
+ if col["type"] == "email":
76
+ return col["name"]
77
+ return None
78
+
79
+
80
+ # --- Key management (signed-in users) ---------------------------------------
81
+
82
+ def _clean_welcome(org_id: str, welcome: dict | None, default_mailbox: str | None) -> dict | None:
83
+ """A welcome email: {subject, html_body, mailbox_connection_id}, or None for no welcome."""
84
+ if not welcome or not (welcome.get("subject") or welcome.get("html_body")):
85
+ return None
86
+ subject, body = str(welcome.get("subject", "")).strip(), str(welcome.get("html_body", "")).strip()
87
+ if not subject or not body:
88
+ raise ValueError("A welcome email needs both a subject and a message")
89
+ mailbox_id = welcome.get("mailbox_connection_id") or default_mailbox
90
+ if not mailbox_id:
91
+ raise ValueError("Pick a mailbox to send the welcome email from")
92
+ if mailboxes.get_mailbox(org_id, mailbox_id)["status"] != "verified":
93
+ raise ValueError("That mailbox is not verified yet, so it cannot send the welcome email.")
94
+ return {"subject": subject, "html_body": body, "mailbox_connection_id": mailbox_id}
95
+
96
+
97
+ def set_welcome(org_id: str, actor_uid: str, key_id: str, welcome: dict | None) -> dict | None:
98
+ orgs.require_permission(org_id, actor_uid, "edit_lists")
99
+ doc = db.get_doc(_key_path(org_id, key_id))
100
+ if doc is None:
101
+ raise orgs.NotFoundError(f"No form {key_id!r}")
102
+ cleaned = _clean_welcome(org_id, welcome, doc.get("mailbox_connection_id"))
103
+ db.update_doc(_key_path(org_id, key_id), {"welcome": cleaned})
104
+ return cleaned
105
+
106
+
107
+ def _send_welcome(org_id: str, key: dict, row_id: str) -> None:
108
+ """Queues the form's welcome email to the one person who just joined. A failure here never
109
+ turns away the sign-up; the person is on the list either way."""
110
+ welcome = key.get("welcome")
111
+ if not welcome:
112
+ return
113
+ from backend import sending # late: sending pulls in much of the app
114
+
115
+ try:
116
+ sending.queue_campaign(
117
+ org_id, key.get("created_by", ""), welcome["subject"], welcome["html_body"], welcome["mailbox_connection_id"],
118
+ key["database_id"], only_row_ids=[row_id], automated=True,
119
+ )
120
+ except Exception: # noqa: BLE001 - see docstring
121
+ logging.getLogger(__name__).exception("Welcome email for form %s could not be queued", key.get("name"))
122
+
123
+
124
+ def create_key(
125
+ org_id: str, actor_uid: str, name: str, database_id: str, allowed_origins: list[str],
126
+ fields: list[str] | None = None, double_opt_in: bool = True,
127
+ mailbox_connection_id: str | None = None, daily_cap: int = C.COLLECT_DEFAULT_DAILY_CAP,
128
+ welcome: dict | None = None,
129
+ ) -> dict:
130
+ orgs.require_permission(org_id, actor_uid, "edit_lists")
131
+ name = name.strip()
132
+ if not name or len(name) > 80:
133
+ raise ValueError("Give the form a name (up to 80 characters)")
134
+ database = databases.get_database(org_id, database_id)
135
+ email_column = _email_column(database)
136
+ if email_column is None:
137
+ raise ValueError("This list has no email column yet, so people cannot sign up to it. Set one first.")
138
+
139
+ column_names = [c["name"] for c in database["columns"]]
140
+ chosen = column_names if not fields else fields
141
+ unknown = [f for f in chosen if f not in column_names]
142
+ if unknown:
143
+ raise ValueError(f"Not a column in this list: {', '.join(unknown)}")
144
+ chosen = [f for f in chosen if not _blocked(f)]
145
+ if email_column not in chosen:
146
+ chosen.insert(0, email_column)
147
+
148
+ if double_opt_in:
149
+ if not mailbox_connection_id:
150
+ raise ValueError("Pick a mailbox to send the confirmation email from, or turn confirmation off.")
151
+ if mailboxes.get_mailbox(org_id, mailbox_connection_id)["status"] != "verified":
152
+ raise ValueError("That mailbox is not verified yet, so it cannot send confirmation emails.")
153
+ if not 1 <= daily_cap <= 10_000:
154
+ raise ValueError("Daily limit must be between 1 and 10,000")
155
+
156
+ origins = list(dict.fromkeys(_normalize_origin(o) for o in allowed_origins if o.strip()))
157
+ key_id = uuid.uuid4().hex
158
+ public_key = "pk_" + secrets.token_urlsafe(18)
159
+ doc = {
160
+ "name": name,
161
+ "database_id": database_id,
162
+ "public_key": public_key,
163
+ "allowed_origins": origins,
164
+ "fields": chosen,
165
+ "double_opt_in": double_opt_in,
166
+ "mailbox_connection_id": mailbox_connection_id if double_opt_in else None,
167
+ "daily_cap": daily_cap,
168
+ "welcome": _clean_welcome(org_id, welcome, mailbox_connection_id),
169
+ "created_by": actor_uid,
170
+ "revoked": False,
171
+ "created_at": _now().isoformat(),
172
+ }
173
+ db.set_doc(_key_path(org_id, key_id), doc)
174
+ db.set_doc(_index_path(public_key), {"org_id": org_id, "key_id": key_id})
175
+ return doc | {"key_id": key_id}
176
+
177
+
178
+ def list_keys(org_id: str, actor_uid: str) -> list[dict]:
179
+ orgs.require_permission(org_id, actor_uid)
180
+ prefix = f"orgs/{org_id}/collect_keys/"
181
+ items = [data | {"key_id": path[len(prefix):]} for path, data in db.query_prefix(prefix).items()]
182
+ return sorted(items, key=lambda k: k["created_at"], reverse=True)
183
+
184
+
185
+ def revoke_key(org_id: str, actor_uid: str, key_id: str) -> None:
186
+ orgs.require_permission(org_id, actor_uid, "edit_lists")
187
+ doc = db.get_doc(_key_path(org_id, key_id))
188
+ if doc is None:
189
+ raise orgs.NotFoundError(f"No form {key_id!r}")
190
+ db.update_doc(_key_path(org_id, key_id), {"revoked": True})
191
+ db.delete_doc(_index_path(doc["public_key"]))
192
+
193
+
194
+ # --- Public side ---------------------------------------------------------------
195
+
196
+ def _load_key(public_key: str) -> tuple[str, str, dict]:
197
+ index = db.get_doc(_index_path(public_key))
198
+ if index is None:
199
+ raise CollectError(404, "Unknown form")
200
+ doc = db.get_doc(_key_path(index["org_id"], index["key_id"]))
201
+ if doc is None or doc["revoked"]:
202
+ raise CollectError(404, "Unknown form")
203
+ return index["org_id"], index["key_id"], doc
204
+
205
+
206
+ def allowed_origin(public_key: str, origin: str | None) -> str | None:
207
+ """The value for Access-Control-Allow-Origin for this key and caller, or None."""
208
+ try:
209
+ _, _, key = _load_key(public_key)
210
+ except CollectError:
211
+ return None
212
+ if not origin:
213
+ return None
214
+ origin = origin.strip().rstrip("/").lower()
215
+ if not key["allowed_origins"] or origin in key["allowed_origins"]:
216
+ return origin
217
+ return None
218
+
219
+
220
+ def submit(public_key: str, payload: object, origin: str | None, client_ip: str) -> dict:
221
+ """Handles one public sign-up. Returns {"ok": True, "pending": bool}. Raises CollectError
222
+ only for things a real visitor or the site owner needs to know about; bots caught by the
223
+ cheap checks get a normal-looking success so they learn nothing."""
224
+ org_id, key_id, key = _load_key(public_key)
225
+ pending_mode = key["double_opt_in"]
226
+ ok = {"ok": True, "pending": pending_mode}
227
+
228
+ if key["allowed_origins"] and (not origin or origin.strip().rstrip("/").lower() not in key["allowed_origins"]):
229
+ raise CollectError(403, "This form is not allowed on this site")
230
+
231
+ if not isinstance(payload, dict) or not isinstance(payload.get("fields"), dict):
232
+ raise CollectError(400, "Malformed submission")
233
+ raw_fields = payload["fields"]
234
+ if len(raw_fields) > C.COLLECT_MAX_FIELDS or len(json.dumps(payload)) > C.COLLECT_MAX_BODY_BYTES:
235
+ raise CollectError(413, "Submission is too large")
236
+
237
+ # Cheap bot checks: honeypot filled, or filled in faster than a person can.
238
+ if payload.get("hp"):
239
+ return ok
240
+ elapsed = payload.get("t")
241
+ if isinstance(elapsed, (int, float)) and elapsed < C.COLLECT_MIN_FILL_SECONDS * 1000:
242
+ return ok
243
+
244
+ if not rate_limiter.allow_hit(f"collect-key:{key_id}", C.COLLECT_PER_KEY_PER_MINUTE, 60):
245
+ raise CollectError(429, "Too many sign-ups right now. Try again in a minute.")
246
+ ip_hash = hashlib.sha256(client_ip.encode()).hexdigest()[:16]
247
+ if not rate_limiter.allow_hit(f"collect-ip:{ip_hash}", C.COLLECT_PER_IP_PER_MINUTE, 60):
248
+ raise CollectError(429, "Too many sign-ups from your connection. Try again in a minute.")
249
+
250
+ database = databases.get_database(org_id, key["database_id"])
251
+ email_column = _email_column(database)
252
+ if email_column is None:
253
+ raise CollectError(409, "This form is not set up correctly")
254
+
255
+ values = {}
256
+ for name, value in raw_fields.items():
257
+ if name not in key["fields"] or _blocked(name) or isinstance(value, (dict, list)):
258
+ continue
259
+ text = str(value).strip()[: C.COLLECT_MAX_VALUE_LENGTH]
260
+ if text:
261
+ values[name] = text
262
+
263
+ email = values.get(email_column, "")
264
+ if not databases.EMAIL_RE.match(email):
265
+ raise CollectError(400, "Please enter a valid email address")
266
+
267
+ if not rate_limiter.allow_hit(f"collect-day:{key_id}", key["daily_cap"], 86_400):
268
+ raise CollectError(429, "This form has reached its daily limit")
269
+
270
+ digest = hashlib.sha256(email.lower().encode()).hexdigest()[:20]
271
+ if not rate_limiter.allow_hit(f"collect-addr:{key_id}:{digest}", C.COLLECT_PER_ADDRESS_PER_HOUR, 3600):
272
+ return ok # already asked recently; do not email them again, do not say so
273
+
274
+ existing = databases.list_rows(org_id, key["database_id"])
275
+ if any(str(r.get(email_column, "")).strip().lower() == email.lower() for r in existing):
276
+ return ok # already on the list; do not reveal that
277
+
278
+ if not pending_mode:
279
+ row_id = databases.insert_row(org_id, key["database_id"], values)
280
+ _record_consent(org_id, row_id, key_id, email)
281
+ _send_welcome(org_id, key, row_id)
282
+ return ok
283
+
284
+ token = secrets.token_urlsafe(24)
285
+ expires = _now() + timedelta(hours=C.COLLECT_CONFIRM_TTL_HOURS)
286
+ db.set_doc(_pending_path(token), {
287
+ "org_id": org_id,
288
+ "key_id": key_id,
289
+ "database_id": key["database_id"],
290
+ "encrypted_values": encrypt(json.dumps(values)),
291
+ "expires_at": expires.isoformat(),
292
+ })
293
+ try:
294
+ _send_confirmation(org_id, key, email, token)
295
+ except CollectError:
296
+ db.delete_doc(_pending_path(token))
297
+ raise
298
+ return ok
299
+
300
+
301
+ def _send_confirmation(org_id: str, key: dict, email: str, token: str) -> None:
302
+ try:
303
+ rate_limiter.check_and_consume(org_id, count=1)
304
+ except rate_limiter.RateLimitExceeded as exc:
305
+ raise CollectError(429, "Confirmation emails are paused for now. Try again later.") from exc
306
+ connection = mailboxes.get_mailbox(org_id, key["mailbox_connection_id"])
307
+ if connection["status"] != "verified":
308
+ raise CollectError(503, "This form cannot send confirmation emails right now")
309
+ org_name = html.escape(orgs.get_org(org_id)["name"])
310
+ base = os.getenv("PUBLIC_API_BASE_URL", "http://localhost:8000").rstrip("/")
311
+ link = f"{base}/collect/confirm/{token}"
312
+ body = (
313
+ f"<p>Please confirm your email address to join {org_name}'s list.</p>"
314
+ f'<p><a href="{html.escape(link)}">Yes, add me</a></p>'
315
+ f"<p>If you did not ask for this, ignore this email and nothing will happen.</p>"
316
+ )
317
+ mailer = mailer_client.get_mailer(connection["kind"], mailboxes.get_decrypted_credentials(org_id, key["mailbox_connection_id"]))
318
+ try:
319
+ mailer.send(to_addr=email, subject=f"Confirm your email for {orgs.get_org(org_id)['name']}", body=body)
320
+ except (AuthError, ConnectionFailure) as exc:
321
+ raise CollectError(503, "Could not send the confirmation email. Try again later.") from exc
322
+
323
+
324
+ def _record_consent(org_id: str, row_id: str, key_id: str, email: str) -> None:
325
+ db.set_doc(_consent_path(org_id, row_id), {
326
+ "key_id": key_id,
327
+ "email_hash": hashlib.sha256(email.lower().encode()).hexdigest(),
328
+ "confirmed_at": _now().isoformat(),
329
+ })
330
+
331
+
332
+ def confirm(token: str) -> str:
333
+ """Turns a pending sign-up into a row. Returns "confirmed", "expired" or "invalid"."""
334
+ pending = db.get_doc(_pending_path(token))
335
+ if pending is None:
336
+ return "invalid"
337
+ if datetime.fromisoformat(pending["expires_at"]) < _now():
338
+ db.delete_doc(_pending_path(token))
339
+ return "expired"
340
+ values = json.loads(decrypt(pending["encrypted_values"]))
341
+ org_id = pending["org_id"]
342
+ db.delete_doc(_pending_path(token)) # single use, even if the insert below fails
343
+ try:
344
+ row_id = databases.insert_row(org_id, pending["database_id"], values)
345
+ except orgs.NotFoundError:
346
+ return "invalid" # the list was deleted since
347
+ email_column = _email_column(databases.get_database(org_id, pending["database_id"]))
348
+ _record_consent(org_id, row_id, pending["key_id"], values.get(email_column or "", ""))
349
+ key = db.get_doc(_key_path(org_id, pending["key_id"]))
350
+ if key:
351
+ _send_welcome(org_id, key, row_id)
352
+ return "confirmed"
backend/collect_api.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The public face of Collect (docs/blueprint/adr/0006) — the "DMZ". Exactly these routes and
3
+ nothing else are reachable without signing in, and each one only calls backend/collect.py.
4
+
5
+ It is an APIRouter so the main app can include it today, and `collect_app` is the same router
6
+ as a standalone ASGI app for deploying on its own later.
7
+
8
+ Cross-origin: the snippet sends its JSON as text/plain, which browsers treat as a "simple"
9
+ request (no preflight), and this module sets Access-Control-Allow-Origin per key itself. The
10
+ site-wide CORS middleware in app.py is for the signed-in app and stays out of the way.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import html
16
+ import json
17
+ from pathlib import Path
18
+
19
+ from fastapi import APIRouter, FastAPI, Request
20
+ from fastapi.responses import HTMLResponse, JSONResponse, Response
21
+
22
+ from backend import collect
23
+
24
+ router = APIRouter()
25
+ _SNIPPET_PATH = Path(__file__).parent / "static" / "m8ion.js"
26
+
27
+
28
+ def _client_ip(request: Request) -> str:
29
+ # Behind a proxy the first X-Forwarded-For entry is the visitor. Only trusted as a rate-limit
30
+ # bucket, never for anything that grants access.
31
+ forwarded = request.headers.get("x-forwarded-for", "")
32
+ if forwarded:
33
+ return forwarded.split(",")[0].strip()
34
+ return request.client.host if request.client else "unknown"
35
+
36
+
37
+ def _with_cors(response: Response, public_key: str, origin: str | None) -> Response:
38
+ allowed = collect.allowed_origin(public_key, origin)
39
+ if allowed:
40
+ response.headers["Access-Control-Allow-Origin"] = allowed
41
+ response.headers["Vary"] = "Origin"
42
+ return response
43
+
44
+
45
+ @router.post("/collect/{public_key}")
46
+ async def submit(public_key: str, request: Request):
47
+ origin = request.headers.get("origin")
48
+ raw = await request.body()
49
+ if len(raw) > 16_000:
50
+ return _with_cors(JSONResponse({"detail": "Submission is too large"}, status_code=413), public_key, origin)
51
+ try:
52
+ payload = json.loads(raw)
53
+ except ValueError:
54
+ return _with_cors(JSONResponse({"detail": "Malformed submission"}, status_code=400), public_key, origin)
55
+ try:
56
+ result = collect.submit(public_key, payload, origin, _client_ip(request))
57
+ response = JSONResponse(result)
58
+ except collect.CollectError as exc:
59
+ response = JSONResponse({"detail": str(exc)}, status_code=exc.status)
60
+ return _with_cors(response, public_key, origin)
61
+
62
+
63
+ _PAGE = """<!doctype html><html lang="en"><head><meta charset="utf-8">
64
+ <meta name="viewport" content="width=device-width,initial-scale=1"><title>{title}</title>
65
+ <style>body{{font-family:system-ui,sans-serif;max-width:32rem;margin:15vh auto;padding:0 1.25rem;color:#1b1f23}}
66
+ h1{{font-size:1.4rem}}p{{color:#555;line-height:1.5}}</style></head>
67
+ <body><h1>{title}</h1><p>{message}</p></body></html>"""
68
+
69
+ _CONFIRM_TEXT = {
70
+ "confirmed": ("You're on the list", "Thanks, your email address is confirmed. You can close this page."),
71
+ "expired": ("This link has expired", "Please sign up again from the form to get a new confirmation email."),
72
+ "invalid": ("This link is no longer valid", "It may already have been used. If you are not on the list yet, sign up again."),
73
+ }
74
+
75
+
76
+ @router.get("/collect/confirm/{token}", response_class=HTMLResponse)
77
+ def confirm(token: str):
78
+ title, message = _CONFIRM_TEXT[collect.confirm(token)]
79
+ return HTMLResponse(_PAGE.format(title=html.escape(title), message=html.escape(message)))
80
+
81
+
82
+ @router.get("/m8ion.js")
83
+ def snippet():
84
+ return Response(
85
+ _SNIPPET_PATH.read_text(encoding="utf-8"),
86
+ media_type="application/javascript",
87
+ headers={"Cache-Control": "public, max-age=300", "Access-Control-Allow-Origin": "*"},
88
+ )
89
+
90
+
91
+ collect_app = FastAPI(title="M8ion Collect")
92
+ collect_app.include_router(router)
backend/config.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Loads .env into the process environment before anything else in backend/ reads os.environ.
3
+ Imported by backend/__init__.py so every submodule sees a populated environment regardless
4
+ of import order.
5
+ """
6
+
7
+ from dotenv import load_dotenv
8
+
9
+ load_dotenv()
backend/core/__init__.py ADDED
File without changes
backend/core/constants.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Central registry for cross-cutting, iteration-prone values.
3
+
4
+ This is the ONE place values like these are defined — every other module imports from
5
+ here, never hand-copies a number or a list. See docs/blueprint/blueprint.md and
6
+ docs/product/checklist.md ("central intelligence... registry") for why this file exists:
7
+ these are exactly the values that change a lot across iterations, and a change here should
8
+ be a visible, deliberate moment, not a silent edit buried in an unrelated diff.
9
+
10
+ scripts/run_tests.py diffs this file against the last commit on every test run and prints
11
+ a notice (not a failure) listing what changed, so a change here is never silent.
12
+
13
+ Every value below marked "prototype placeholder" is not a business decision — it exists so
14
+ local development and tests have something concrete to run against, and is expected to be
15
+ replaced with a real, deliberately-chosen number before Phase 2.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ # ---------------------------------------------------------------------------
21
+ # Versioning
22
+ # ---------------------------------------------------------------------------
23
+
24
+ # Application version. Bump on every meaningful release (Phase 4 onward, this drives
25
+ # docs/general/CHANGELOG.md entries).
26
+ APP_VERSION = "0.1.0-proto"
27
+
28
+ # Schema version for the data model. Bump when a migration changes stored-data shape in a
29
+ # way that old rows won't automatically satisfy — not on every schema tweak.
30
+ SCHEMA_VERSION = "0.1.0"
31
+
32
+ # ---------------------------------------------------------------------------
33
+ # Org roles — see docs/blueprint/blueprint.md "Core entities"
34
+ # ---------------------------------------------------------------------------
35
+
36
+ # Ranked low to high. An action gated at a given role is allowed for that role and every
37
+ # role ranked above it (e.g. a check gated at "operator" also passes for "admin"/"owner").
38
+ ROLE_RANK: dict[str, int] = {
39
+ "viewer": 0,
40
+ "operator": 1,
41
+ "editor": 1,
42
+ "admin": 2,
43
+ "owner": 3,
44
+ }
45
+
46
+ # What a role can be allowed to do. Seeing the org's results is not on this list: every
47
+ # member can always see them. Labels are shown to owners when they set up a role.
48
+ PERMISSIONS: dict[str, str] = {
49
+ "edit_lists": "Add and change lists and sign-up forms",
50
+ "edit_emails": "Create and change saved emails and looks",
51
+ "send": "Send campaigns",
52
+ "manage_mailboxes": "Connect and manage mailboxes",
53
+ "manage_settings": "Change organisation settings",
54
+ "manage_team": "Invite people and change their roles",
55
+ }
56
+
57
+ # Roles every org starts with. Owner always has everything and can't be changed; the
58
+ # others are starting points an owner can edit. Custom roles sit beside these.
59
+ BUILTIN_ROLES: dict[str, dict] = {
60
+ "owner": {"name": "Owner", "permissions": list(PERMISSIONS)},
61
+ "admin": {"name": "Admin", "permissions": list(PERMISSIONS)},
62
+ "editor": {"name": "Editor", "permissions": ["edit_lists", "edit_emails", "send"]},
63
+ "viewer": {"name": "Viewer", "permissions": []},
64
+ "director": {"name": "Director", "permissions": []},
65
+ "accountant": {"name": "Accountant", "permissions": []},
66
+ "marketer": {"name": "Marketer", "permissions": ["edit_lists", "edit_emails", "send"]},
67
+ "auditor": {"name": "Auditor", "permissions": []},
68
+ }
69
+
70
+ # The areas of an organisation (/org/<key>). Everyone in the org sees every area listed; an
71
+ # area opens only for a member whose role (or extra roles) carries it. More will be added.
72
+ SPACES: dict[str, tuple[str, str]] = {
73
+ "admin": ("Admin", "Team, mailboxes and organisation settings."),
74
+ "director": ("Director", "How the whole organisation is doing."),
75
+ "accountant": ("Accountant", "Receipts and money matters."),
76
+ "marketer": ("Marketer", "Campaigns, audiences and presets."),
77
+ "auditor": ("Auditor", "A read-only look at what was done and by whom."),
78
+ }
79
+
80
+ # Which areas each role opens. Owner opens all. Admin opens all except accountant and director.
81
+ ROLE_SPACES: dict[str, list[str]] = {
82
+ "owner": list(SPACES),
83
+ "admin": ["admin", "marketer", "auditor"],
84
+ "director": ["director"],
85
+ "accountant": ["accountant"],
86
+ "marketer": ["marketer"],
87
+ "editor": ["marketer"],
88
+ "auditor": ["auditor"],
89
+ }
90
+
91
+ # Older stored role names, read as their current equivalent.
92
+ ROLE_ALIASES: dict[str, str] = {"operator": "editor"}
93
+
94
+ # Days an invite link stays usable.
95
+ INVITE_TTL_DAYS = 7
96
+
97
+ # The role assigned automatically to whoever creates an org. Not assignable via
98
+ # add_member — ownership only exists by creating the org (transfer is out of scope for now).
99
+ ORG_CREATOR_ROLE = "owner"
100
+
101
+ # ---------------------------------------------------------------------------
102
+ # Mailbox connections — see docs/blueprint/adr/0001-relay-not-esp.md
103
+ # ---------------------------------------------------------------------------
104
+
105
+ # Providers that get the OAuth path. Everything else falls through to raw SMTP credentials.
106
+ SUPPORTED_OAUTH_PROVIDERS: tuple[str, ...] = ("gmail", "outlook", "yahoo")
107
+
108
+ # Days between changes to a connected mailbox's sign-in details (a change re-runs the test).
109
+ MAILBOX_CREDENTIAL_CHANGE_DAYS = 30
110
+
111
+ # Highest daily send limit an org can set on one mailbox. 0 means no limit of our own.
112
+ MAILBOX_DAILY_LIMIT_MAX = 10_000
113
+
114
+ # Number of OTP verification messages sent in the mailbox-connection round-trip
115
+ # (docs/product/srs.md FR-6).
116
+ VERIFICATION_OTP_COUNT = 3
117
+
118
+ # Seconds to wait for all VERIFICATION_OTP_COUNT messages to arrive before treating the
119
+ # connection as a silent failure (SRS FR-7). Prototype placeholder.
120
+ VERIFICATION_TIMEOUT_SECONDS = 300
121
+
122
+ # ---------------------------------------------------------------------------
123
+ # Rate limiting & abuse prevention — see docs/blueprint/blueprint.md "Rate limiting"
124
+ # ---------------------------------------------------------------------------
125
+
126
+ # Default hourly send cap per account, enforced server-side via a rolling token bucket.
127
+ # Prototype placeholder — real tiering happens in PLAN_TIERS below once pricing is set.
128
+ DEFAULT_HOURLY_SEND_CAP = 100
129
+
130
+ # Escalation stages for anomaly detection, in order. Each stage's threshold is a multiple
131
+ # of the account's own rolling baseline rate, not an absolute number.
132
+ RATE_ANOMALY_ESCALATION_STAGES: tuple[str, ...] = (
133
+ "detect",
134
+ "block",
135
+ "silently_report",
136
+ "auto_temporary_ban",
137
+ )
138
+
139
+ # ---------------------------------------------------------------------------
140
+ # Bounce handling — see docs/blueprint/blueprint.md "Sending pipeline"
141
+ # ---------------------------------------------------------------------------
142
+
143
+ # Soft-bounce retry ceiling before escalating to a person. Prototype placeholder.
144
+ SOFT_BOUNCE_RETRY_CEILING = 5
145
+
146
+ # Backoff schedule (seconds) between soft-bounce retries, up to the ceiling above.
147
+ SOFT_BOUNCE_BACKOFF_SECONDS: tuple[int, ...] = (60, 300, 900, 3600, 14400)
148
+
149
+ # Initial window (seconds) to match an inbound message to a specific sent OTP/message by
150
+ # direct reference before escalating to the broader regex rescan pass.
151
+ BOUNCE_MATCH_INITIAL_WINDOW_SECONDS = 120
152
+
153
+ # ---------------------------------------------------------------------------
154
+ # Billing — see docs/blueprint/adr/0005-per-recipient-pay-as-you-go-billing.md
155
+ # ---------------------------------------------------------------------------
156
+
157
+ # Soft-cap usage warning thresholds, as a fraction of an org's monthly free allowance.
158
+ # Fires on all 3 surfaces (email, in-app, control panel banner) per SRS FR-28.
159
+ SOFT_CAP_WARNING_THRESHOLDS: tuple[float, ...] = (0.8, 1.0)
160
+
161
+ # Plan tiers. Real pricing/allowances are a business decision (see ADR-0005) — these are
162
+ # structural placeholders so the billing code has real shapes to run tests against.
163
+ PLAN_TIERS: dict[str, dict[str, object]] = {
164
+ "free": {
165
+ "monthly_recipient_allowance": 500, # prototype placeholder
166
+ "hourly_send_cap": DEFAULT_HOURLY_SEND_CAP,
167
+ "storage_mb": 250, # prototype placeholder
168
+ "overage_allowed": False,
169
+ },
170
+ "paid": {
171
+ "monthly_recipient_allowance": None, # unlimited within pay-as-you-go
172
+ "hourly_send_cap": DEFAULT_HOURLY_SEND_CAP * 5, # prototype placeholder
173
+ "storage_mb": 5000, # prototype placeholder
174
+ "overage_allowed": True,
175
+ },
176
+ }
177
+
178
+ # ---------------------------------------------------------------------------
179
+ # M8ion's own outbound identity — see docs/blueprint/blueprint.md "M8ion's own outbound mail"
180
+ # ---------------------------------------------------------------------------
181
+
182
+ # Prototype-only sending address for M8ion's own transactional mail. Replaced with a real
183
+ # registered domain before Phase 3.
184
+ SYSTEM_SENDER_ADDRESS_PROTO = "projects.techies.26@gmail.com"
185
+
186
+ # The receiving side of the mailbox-verification round-trip (SRS FR-6) — "M8ion's own test
187
+ # mailbox". Prototype placeholder; becomes a real address once a domain is registered.
188
+ SYSTEM_TEST_MAILBOX_ADDRESS_PROTO = "verify-test@m8ion-test.local"
189
+
190
+ # ---------------------------------------------------------------------------
191
+ # Public collection endpoint (docs/blueprint/adr/0006) — all prototype placeholders
192
+ # ---------------------------------------------------------------------------
193
+
194
+ COLLECT_MAX_BODY_BYTES = 8_000
195
+ COLLECT_MAX_FIELDS = 30
196
+ COLLECT_MAX_VALUE_LENGTH = 500
197
+ COLLECT_MIN_FILL_SECONDS = 2 # a human cannot fill a form faster than this
198
+ COLLECT_PER_KEY_PER_MINUTE = 30
199
+ COLLECT_PER_IP_PER_MINUTE = 10
200
+ COLLECT_PER_ADDRESS_PER_HOUR = 1 # confirmation emails to one address, per key
201
+ COLLECT_DEFAULT_DAILY_CAP = 500
202
+ COLLECT_CONFIRM_TTL_HOURS = 48
203
+ # Field names that are never collected, whatever the key allows.
204
+ COLLECT_BLOCKED_FIELD_WORDS = ("password", "passwd", "pwd", "card", "cvv", "cvc", "ssn", "secret", "token")
backend/crypto_utils.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Prototype-only stand-in for ADR-0002's GCP KMS envelope encryption. No GCP project is
3
+ provisioned yet (see docs/blueprint/blueprint.md), so mailbox credentials and contact PII
4
+ are encrypted at rest here using a single symmetric Fernet key from CREDENTIAL_ENCRYPTION_KEY
5
+ (.env) instead of KMS-wrapped per-record data keys.
6
+
7
+ This is a real, working encryption layer — not a no-op — but it is NOT the security posture
8
+ ADR-0002 commits to for production: one key, no envelope, no separate audit-logged access
9
+ control. Every function here is the seam that gets replaced (same call signatures) once a
10
+ GCP project with KMS exists.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+
17
+ from cryptography.fernet import Fernet
18
+
19
+ _key = os.getenv("CREDENTIAL_ENCRYPTION_KEY")
20
+ if not _key:
21
+ # Auto-generated per-process when unset, matching the prior build's local-dev fallback.
22
+ # Encrypted values won't survive a process restart with a fresh key — fine for tests
23
+ # and throwaway local runs, NOT fine for anything meant to persist. Set
24
+ # CREDENTIAL_ENCRYPTION_KEY in .env for a stable local key across restarts.
25
+ _key = Fernet.generate_key().decode()
26
+
27
+ _fernet = Fernet(_key.encode() if isinstance(_key, str) else _key)
28
+
29
+
30
+ def encrypt(plaintext: str) -> str:
31
+ return _fernet.encrypt(plaintext.encode()).decode()
32
+
33
+
34
+ def decrypt(token: str) -> str:
35
+ return _fernet.decrypt(token.encode()).decode()
backend/customizations.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Saved email "customizations" — a named header + footer + brand color a company designs once
3
+ and picks per campaign, instead of redesigning them on every send. Stored per org at
4
+ orgs/{org_id}/customizations/{id}. The frontend merges the chosen customization around the
5
+ message body into the final HTML (frontend/src/lib/emailFrame.ts), so sending itself is
6
+ unchanged and never needs to know which customization was used.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ import uuid
13
+ from datetime import datetime, timezone
14
+
15
+ from backend import firestore_client as db
16
+ from backend import orgs
17
+
18
+ _COLOR_RE = re.compile(r"^#[0-9a-fA-F]{6}$")
19
+ _MAX_NAME = 80
20
+ _MAX_HTML = 20_000
21
+
22
+
23
+ def _now() -> str:
24
+ return datetime.now(timezone.utc).isoformat()
25
+
26
+
27
+ def _prefix(org_id: str) -> str:
28
+ return f"orgs/{org_id}/customizations/"
29
+
30
+
31
+ def _path(org_id: str, customization_id: str) -> str:
32
+ return f"{_prefix(org_id)}{customization_id}"
33
+
34
+
35
+ def _clean(name: str, brand_color: str, logo_url: str, header_text: str, footer_html: str, footer_bg: str) -> dict:
36
+ name = name.strip()
37
+ if not name or len(name) > _MAX_NAME:
38
+ raise ValueError(f"Name is required and must be at most {_MAX_NAME} characters")
39
+ if not _COLOR_RE.match(brand_color):
40
+ raise ValueError("Brand color must be a hex color like #c0392b")
41
+ if not _COLOR_RE.match(footer_bg):
42
+ raise ValueError("Footer background must be a hex color like #f4f4f4")
43
+ logo_url = logo_url.strip()
44
+ if logo_url and not logo_url.lower().startswith("https://"):
45
+ raise ValueError("Logo URL must start with https://")
46
+ if len(footer_html) > _MAX_HTML or len(header_text) > 200:
47
+ raise ValueError("Header or footer is too long")
48
+ return {
49
+ "name": name,
50
+ "brand_color": brand_color,
51
+ "logo_url": logo_url,
52
+ "header_text": header_text.strip(),
53
+ "footer_html": footer_html,
54
+ "footer_bg": footer_bg,
55
+ }
56
+
57
+
58
+ def create_customization(org_id: str, actor_uid: str, name: str, brand_color: str, logo_url: str,
59
+ header_text: str, footer_html: str, footer_bg: str = "#f4f4f4") -> str:
60
+ orgs.require_permission(org_id, actor_uid, "edit_emails")
61
+ data = _clean(name, brand_color, logo_url, header_text, footer_html, footer_bg)
62
+ customization_id = uuid.uuid4().hex
63
+ db.set_doc(_path(org_id, customization_id), data | {"created_at": _now(), "updated_at": _now()})
64
+ return customization_id
65
+
66
+
67
+ def update_customization(org_id: str, actor_uid: str, customization_id: str, name: str, brand_color: str,
68
+ logo_url: str, header_text: str, footer_html: str, footer_bg: str = "#f4f4f4") -> None:
69
+ orgs.require_permission(org_id, actor_uid, "edit_emails")
70
+ get_customization(org_id, customization_id)
71
+ data = _clean(name, brand_color, logo_url, header_text, footer_html, footer_bg)
72
+ db.update_doc(_path(org_id, customization_id), data | {"updated_at": _now()})
73
+
74
+
75
+ def delete_customization(org_id: str, actor_uid: str, customization_id: str) -> None:
76
+ orgs.require_permission(org_id, actor_uid, "edit_emails")
77
+ get_customization(org_id, customization_id)
78
+ db.delete_doc(_path(org_id, customization_id))
79
+
80
+
81
+ def get_customization(org_id: str, customization_id: str) -> dict:
82
+ doc = db.get_doc(_path(org_id, customization_id))
83
+ if doc is None:
84
+ raise orgs.NotFoundError(f"No customization {customization_id!r} in org {org_id!r}")
85
+ return doc
86
+
87
+
88
+ def list_customizations(org_id: str, actor_uid: str) -> dict[str, dict]:
89
+ orgs.require_permission(org_id, actor_uid)
90
+ prefix = _prefix(org_id)
91
+ return {path[len(prefix):]: data for path, data in db.query_prefix(prefix).items()}
backend/databases.py ADDED
@@ -0,0 +1,835 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Audience "databases" — a parsed upload (CSV/XLSX/JSON), cleaned, classified, and normalized
3
+ (see backend/normalize.py for exactly what "normalized" means here and why it stops short of
4
+ blind full 5NF). Replaces the old flat backend/audiences.py contact list: a row now belongs to
5
+ a named, typed database rather than floating in one flat per-org list.
6
+
7
+ Column types: email, contact (phone), name, tag, bool, link, text (default). The auto-
8
+ classifier runs once at upload time; a column's type can be changed later via
9
+ update_column_type, which requires at least one existing value to conform to the new type's
10
+ syntax and flags (not blocks) every row that doesn't.
11
+
12
+ Encryption follows the same posture as the old contacts module (SRS FR-15): row data and
13
+ lookup-table data are both encrypted at rest via backend.crypto_utils, same mechanism as
14
+ mailbox credentials.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import csv
20
+ import io
21
+ import json
22
+ import re
23
+ import uuid
24
+ from datetime import datetime, timezone
25
+
26
+ from backend import firestore_client as db
27
+ from backend import normalize
28
+ from backend.templating import split_items
29
+ from backend import orgs
30
+ from backend.crypto_utils import decrypt, encrypt
31
+
32
+ COLUMN_TYPES: tuple[str, ...] = ("email", "contact", "name", "tag", "bool", "link", "date", "text")
33
+
34
+ EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
35
+ # Sheets exports often prefix phone numbers with a stray apostrophe ('+234...) to stop them
36
+ # being read as numbers; tolerate it rather than call the whole column text.
37
+ PHONE_RE = re.compile(r"^'?\+?[\d][\d\s\-().]{5,}$")
38
+ # Dates and timestamps: 2004-05-17, 2024/03/09 14:22:01 GMT+1, 17/05/2004, 17 May 2004,
39
+ # 2025-01-02T10:00:00.000Z. Checked before PHONE_RE, which would otherwise swallow digits-and-dashes.
40
+ _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})?)?)?"
41
+ DATE_RE = re.compile(
42
+ rf"^(\d{{4}}[-/.]\d{{1,2}}[-/.]\d{{1,2}}([ T]{_TIME})?"
43
+ rf"|\d{{1,2}}[-/.]\d{{1,2}}[-/.]\d{{2,4}}([ T]{_TIME})?"
44
+ r"|\d{1,2}\s+[A-Za-z]{3,9}\.?,?\s+\d{4}"
45
+ r"|[A-Za-z]{3,9}\.?\s+\d{1,2},?\s+\d{4})$",
46
+ re.IGNORECASE,
47
+ )
48
+ # "18 - 24", "25-34": a range of small numbers, not a phone number.
49
+ RANGE_RE = re.compile(r"^\d{1,3}\s*(-|to|–)\s*\d{1,3}\+?$|^\d{1,3}\+$", re.IGNORECASE)
50
+ URL_RE = re.compile(r"^(https?://|www\.)\S+$", re.IGNORECASE)
51
+ BOOL_VALUES = {"true", "false", "yes", "no", "y", "n", "1", "0"}
52
+
53
+ # None of these three ever raise for an empty cell — an unfilled field isn't a conformance
54
+ # failure, only a filled-but-malformed one is.
55
+ TYPE_VALIDATORS = {
56
+ "email": lambda v: bool(EMAIL_RE.match(v.strip())),
57
+ "contact": lambda v: bool(PHONE_RE.match(v.strip())) and not DATE_RE.match(v.strip()),
58
+ "date": lambda v: bool(DATE_RE.match(v.strip())),
59
+ "link": lambda v: bool(URL_RE.match(v.strip())),
60
+ "bool": lambda v: v.strip().lower() in BOOL_VALUES,
61
+ }
62
+
63
+
64
+ class ValidationError(Exception):
65
+ pass
66
+
67
+
68
+ def _now() -> str:
69
+ return datetime.now(timezone.utc).isoformat()
70
+
71
+
72
+ def _database_path(org_id: str, database_id: str) -> str:
73
+ return f"orgs/{org_id}/databases/{database_id}"
74
+
75
+
76
+ def _row_path(org_id: str, database_id: str, row_id: str) -> str:
77
+ return f"orgs/{org_id}/databases/{database_id}/rows/{row_id}"
78
+
79
+
80
+ def _rows_prefix(org_id: str, database_id: str) -> str:
81
+ return f"orgs/{org_id}/databases/{database_id}/rows/"
82
+
83
+
84
+ def _lookup_path(org_id: str, database_id: str, lookup_name: str) -> str:
85
+ return f"orgs/{org_id}/databases/{database_id}/lookups/{lookup_name}"
86
+
87
+
88
+ # --- Parsing ------------------------------------------------------------------
89
+
90
+ def _parse_csv(file_bytes: bytes) -> tuple[list[str], list[dict]]:
91
+ text = file_bytes.decode("utf-8-sig")
92
+ reader = csv.DictReader(io.StringIO(text))
93
+ headers = list(reader.fieldnames or [])
94
+ return headers, [dict(row) for row in reader]
95
+
96
+
97
+ def _parse_json(file_bytes: bytes) -> tuple[list[str], list[dict]]:
98
+ data = json.loads(file_bytes.decode("utf-8"))
99
+ if isinstance(data, dict):
100
+ data = data.get("rows") or data.get("data") or list(data.values())
101
+ if not isinstance(data, list) or not data or not all(isinstance(r, dict) for r in data):
102
+ raise ValidationError("JSON upload must be a non-empty array of objects")
103
+ headers = list(dict.fromkeys(k for row in data for k in row.keys()))
104
+ return headers, [{h: row.get(h) for h in headers} for row in data]
105
+
106
+
107
+ def _parse_xlsx(file_bytes: bytes) -> tuple[list[str], list[dict]]:
108
+ import openpyxl # only needed for this one branch — keep the import lazy
109
+
110
+ workbook = openpyxl.load_workbook(io.BytesIO(file_bytes), read_only=True, data_only=True)
111
+ sheet = workbook.active
112
+ rows_iter = sheet.iter_rows(values_only=True)
113
+ try:
114
+ header_row = next(rows_iter)
115
+ except StopIteration:
116
+ raise ValidationError("Spreadsheet has no rows")
117
+ headers = [str(h) if h is not None else "" for h in header_row]
118
+ rows = [
119
+ {headers[i]: (r[i] if i < len(r) else None) for i in range(len(headers))}
120
+ for r in rows_iter
121
+ ]
122
+ return headers, rows
123
+
124
+
125
+ _PARSERS = {"csv": _parse_csv, "json": _parse_json, "xlsx": _parse_xlsx, "xls": _parse_xlsx}
126
+
127
+
128
+ def _clean(headers: list[str], rows: list[dict]) -> tuple[list[str], list[dict]]:
129
+ """Trims whitespace, drops blank/duplicate headers, drops fully-empty rows and columns."""
130
+ deduped: list[str] = []
131
+ seen: set[str] = set()
132
+ for h in headers:
133
+ h = (h or "").strip()
134
+ if not h:
135
+ continue
136
+ base, i = h, 1
137
+ while h in seen:
138
+ i += 1
139
+ h = f"{base}_{i}"
140
+ seen.add(h)
141
+ deduped.append(h)
142
+
143
+ cleaned_rows = []
144
+ for row in rows:
145
+ new_row = {h: (str(row.get(h)).strip() if row.get(h) not in (None, "") else "") for h in deduped}
146
+ if any(new_row.values()):
147
+ cleaned_rows.append(new_row)
148
+
149
+ nonempty_cols = [h for h in deduped if any(r[h] for r in cleaned_rows)]
150
+ cleaned_rows = [{h: r[h] for h in nonempty_cols} for r in cleaned_rows]
151
+ return nonempty_cols, cleaned_rows
152
+
153
+
154
+ # --- Classification -------------------------------------------------------------
155
+
156
+ def _match_ratio(values: list[str], predicate) -> float:
157
+ nonempty = [v for v in values if v]
158
+ if not nonempty:
159
+ return 0.0
160
+ return sum(1 for v in nonempty if predicate(v)) / len(nonempty)
161
+
162
+
163
+ _PERSON_HEADER_RE = re.compile(r"^(full |first |last |sur|given |your |participant |contact )?(name|surname|fullname)\b", re.IGNORECASE)
164
+
165
+
166
+ def _looks_like_person_name_header(header: str) -> bool:
167
+ """A header that merely *contains* "name" is often not a person ("Name of School /
168
+ Institution", "Username", "Company name"): only headers that lead with name-ish words count."""
169
+ return bool(_PERSON_HEADER_RE.match(header.strip())) and not re.search(
170
+ r"\b(of|school|institution|organi[sz]ation|company|business|user|file|team|group)\b", header, re.IGNORECASE
171
+ )
172
+
173
+
174
+ def classify_column(header: str, values: list[str]) -> str:
175
+ if _match_ratio(values, lambda v: bool(EMAIL_RE.match(v))) >= 0.6:
176
+ return "email"
177
+ if _match_ratio(values, lambda v: bool(URL_RE.match(v))) >= 0.6:
178
+ return "link"
179
+ if _match_ratio(values, lambda v: v.lower() in BOOL_VALUES) >= 0.9:
180
+ return "bool"
181
+ if _match_ratio(values, lambda v: bool(DATE_RE.match(v))) >= 0.6:
182
+ return "date"
183
+ if _match_ratio(values, lambda v: bool(PHONE_RE.match(v)) and not RANGE_RE.match(v)) >= 0.6:
184
+ return "contact"
185
+ if _match_ratio(values, lambda v: ";" in v) >= 0.3:
186
+ return "tag"
187
+ if _looks_like_person_name_header(header):
188
+ return "name"
189
+ return "text"
190
+
191
+
192
+ LIST_DELIMITERS = (";", ",", "|", "\n", "mixed")
193
+
194
+
195
+ def detect_list_delimiter(values: list[str]) -> str | None:
196
+ """Looks for a separator that makes this column a list of short items ("Acme, Beta Ltd").
197
+ Returns the delimiter or None. Deliberately conservative: it only ever feeds a *suggestion*
198
+ the user confirms, because commas also appear in names ("Smith, John") and sentences."""
199
+ nonempty = [v for v in values if v]
200
+ if len(nonempty) < 2:
201
+ return None
202
+
203
+ def qualifies(delim: str) -> bool:
204
+ parts = [split_items(v, delim) for v in nonempty if (delim in v if delim != "mixed" else re.search(r"[;,|\n]", v))]
205
+ if len(parts) < 2 or len(parts) / len(nonempty) < 0.3:
206
+ return False
207
+ items = [i for p in parts for i in p]
208
+ if not items or any(len(i) > 60 for i in items):
209
+ return False
210
+ # Sentences have long "items"; lists of names/events/tags have short ones.
211
+ return sum(len(i.split()) for i in items) / len(items) <= 4
212
+
213
+ ratios = {d: sum(1 for v in nonempty if d in v) / len(nonempty) for d in (";", ",", "|", "\n")}
214
+ if ratios[";"] >= 0.2 and ratios[","] >= 0.2 and qualifies("mixed"):
215
+ return "mixed"
216
+ for delim in sorted(ratios, key=lambda d: -ratios[d]):
217
+ if ratios[delim] >= 0.3 and qualifies(delim):
218
+ return delim
219
+ return None
220
+
221
+
222
+ def _has_conforming_value(values: list[str], new_type: str) -> bool:
223
+ validator = TYPE_VALIDATORS.get(new_type)
224
+ if validator is None:
225
+ return True # name/tag/text have no syntax to conform to
226
+ nonempty = [v for v in values if v]
227
+ return not nonempty or any(validator(v) for v in nonempty)
228
+
229
+
230
+ def _flagged_values(values: list[str], col_type: str) -> list[int]:
231
+ validator = TYPE_VALIDATORS.get(col_type)
232
+ if validator is None:
233
+ return []
234
+ return [i for i, v in enumerate(values) if v and not validator(v)]
235
+
236
+
237
+ def _assign_row_ids(rows: list[dict]) -> list[tuple[str, dict]]:
238
+ return [(uuid.uuid4().hex, row) for row in rows]
239
+
240
+
241
+ def _columns_with_flags(column_types: dict[str, str], headers: list[str], id_rows: list[tuple[str, dict]]) -> list[dict]:
242
+ """Flags non-conforming values up front, at classification time — not only when a column's
243
+ type is changed later. An auto-classified "email" column with one bad row should show that
244
+ immediately, the same as a manual type change would."""
245
+ columns = []
246
+ for h in headers:
247
+ values = [row.get(h, "") for _, row in id_rows]
248
+ flagged_indices = _flagged_values(values, column_types[h])
249
+ col = {
250
+ "name": h,
251
+ "type": column_types[h],
252
+ "flagged_row_ids": [id_rows[i][0] for i in flagged_indices],
253
+ }
254
+ if col["type"] == "tag":
255
+ col["delimiter"] = detect_list_delimiter(values) or ";"
256
+ elif col["type"] in ("text", "name"):
257
+ suggested = detect_list_delimiter(values)
258
+ if suggested:
259
+ col["list_suggestion"] = suggested
260
+ columns.append(col)
261
+ return columns
262
+
263
+
264
+ # --- Upload / create ------------------------------------------------------------
265
+
266
+ def create_database_from_upload(
267
+ org_id: str, actor_uid: str, name: str, file_bytes: bytes, filename: str,
268
+ save_copy=None,
269
+ ) -> str:
270
+ """save_copy(database_id, ext, file_bytes) -> None is injected rather than hardcoded so
271
+ this stays unit-testable without touching disk; the real implementation lives in app.py's
272
+ route (writes to uploads/{org_id}/{database_id}.{ext})."""
273
+ orgs.require_permission(org_id, actor_uid, "edit_lists")
274
+
275
+ ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
276
+ parser = _PARSERS.get(ext)
277
+ if parser is None:
278
+ raise ValidationError(f"Unsupported file type {filename!r} — use .csv, .xlsx, or .json")
279
+
280
+ headers, rows = parser(file_bytes)
281
+ headers, rows = _clean(headers, rows)
282
+ if not headers or not rows:
283
+ raise ValidationError("No usable data found in that file after cleaning")
284
+
285
+ column_types = {h: classify_column(h, [r[h] for r in rows]) for h in headers}
286
+ identity_columns = {h for h in headers if column_types[h] in ("email", "contact")}
287
+ result = normalize.normalize(rows, headers, exclude_determinants=identity_columns, auto_split=False)
288
+
289
+ database_id = uuid.uuid4().hex
290
+ if save_copy:
291
+ save_copy(database_id, ext, file_bytes)
292
+
293
+ id_rows = _assign_row_ids(result.root.rows)
294
+ columns = _columns_with_flags(column_types, result.root.columns, id_rows)
295
+
296
+ db.set_doc(_database_path(org_id, database_id), {
297
+ "name": name,
298
+ "source_filename": filename,
299
+ "source_kind": "xlsx" if ext in ("xlsx", "xls") else ext,
300
+ "created_at": _now(),
301
+ "row_count": len(result.root.rows),
302
+ "columns": columns,
303
+ "lookup_tables": [{"name": t.name, "columns": t.columns} for t in result.lookups],
304
+ "suggestions": result.suggestions,
305
+ })
306
+
307
+ for lookup in result.lookups:
308
+ db.set_doc(_lookup_path(org_id, database_id, lookup.name), {
309
+ "columns": lookup.columns,
310
+ "encrypted_rows": encrypt(json.dumps(lookup.rows)),
311
+ })
312
+
313
+ for row_id, row in id_rows:
314
+ db.set_doc(_row_path(org_id, database_id, row_id), {"encrypted_data": encrypt(json.dumps(row))})
315
+
316
+ return database_id
317
+
318
+
319
+ def get_database(org_id: str, database_id: str) -> dict:
320
+ doc = db.get_doc(_database_path(org_id, database_id))
321
+ if doc is None:
322
+ raise orgs.NotFoundError(f"No database {database_id!r} in org {org_id!r}")
323
+ return doc
324
+
325
+
326
+ def list_databases(org_id: str) -> dict[str, dict]:
327
+ prefix = f"orgs/{org_id}/databases/"
328
+ docs = db.query_prefix(prefix)
329
+ return {path[len(prefix):]: data for path, data in docs.items()}
330
+
331
+
332
+ def list_rows(org_id: str, database_id: str, search: str | None = None, sort: str | None = None) -> list[dict]:
333
+ """Every row, decrypted, with its row_id — client-side-sized (prototype scale), so search
334
+ and sort both happen here in Python rather than needing a real query engine."""
335
+ prefix = _rows_prefix(org_id, database_id)
336
+ docs = db.query_prefix(prefix)
337
+ rows = []
338
+ for path, data in docs.items():
339
+ row = json.loads(decrypt(data["encrypted_data"]))
340
+ row["row_id"] = path[len(prefix):]
341
+ rows.append(row)
342
+
343
+ if search:
344
+ needle = search.strip().lower()
345
+ rows = [r for r in rows if any(needle in str(v).lower() for v in r.values())]
346
+
347
+ if sort:
348
+ rows.sort(key=lambda r: (r.get(sort) is None, str(r.get(sort, "")).lower()))
349
+
350
+ return rows
351
+
352
+
353
+ # Operators a segment condition can use. Which ones make sense depends on the column's type —
354
+ # SEGMENT_OPERATORS_BY_TYPE below is what the frontend uses to only offer valid ones, but
355
+ # _row_matches tolerates any operator against any column rather than erroring, since a changed
356
+ # column type shouldn't break a condition written before the change.
357
+ SEGMENT_OPERATORS_BY_TYPE: dict[str, tuple[str, ...]] = {
358
+ "bool": ("is_true", "is_false", "is_empty", "is_not_empty"),
359
+ "tag": ("has_tag", "lacks_tag", "is_empty", "is_not_empty"),
360
+ }
361
+ _DEFAULT_OPERATORS = ("equals", "not_equals", "contains", "not_contains", "is_empty", "is_not_empty")
362
+
363
+
364
+ def _row_matches(row: dict, col_type: str, field: str, op: str, value: str, delimiter: str | None = None) -> bool:
365
+ text = str(row.get(field, "") or "")
366
+
367
+ if op == "is_empty":
368
+ return text.strip() == ""
369
+ if op == "is_not_empty":
370
+ return text.strip() != ""
371
+
372
+ if col_type == "bool":
373
+ truthy = text.strip().lower() in {"true", "yes", "y", "1"}
374
+ if op == "is_true":
375
+ return truthy
376
+ if op == "is_false":
377
+ return not truthy
378
+
379
+ if col_type == "tag":
380
+ tags = {t.lower() for t in split_items(text, delimiter)}
381
+ needle = value.strip().lower()
382
+ if op == "has_tag":
383
+ return needle in tags
384
+ if op == "lacks_tag":
385
+ return needle not in tags
386
+
387
+ needle = value.strip().lower()
388
+ hay = text.strip().lower()
389
+ if op == "equals":
390
+ return hay == needle
391
+ if op == "not_equals":
392
+ return hay != needle
393
+ if op == "contains":
394
+ return needle in hay
395
+ if op == "not_contains":
396
+ return needle not in hay
397
+ return True
398
+
399
+
400
+ def apply_segment(rows: list[dict], columns: list[dict], conditions: list[dict]) -> list[dict]:
401
+ """Narrows `rows` to only those matching every condition (AND). Each condition is
402
+ {field, op, value}; unknown fields match nothing (a stale condition from a since-removed
403
+ column shouldn't silently widen a send back out to everyone)."""
404
+ col_types = {c["name"]: c["type"] for c in columns}
405
+ delimiters = {c["name"]: c.get("delimiter") for c in columns}
406
+ matched = rows
407
+ for cond in conditions:
408
+ field = cond.get("field", "")
409
+ if field not in col_types:
410
+ return []
411
+ op = cond.get("op", "")
412
+ value = str(cond.get("value", ""))
413
+ col_type = col_types[field]
414
+ matched = [r for r in matched if _row_matches(r, col_type, field, op, value, delimiters[field])]
415
+ return matched
416
+
417
+
418
+ def preview_segment(org_id: str, database_id: str, conditions: list[dict]) -> dict:
419
+ """Live "how many recipients does this match" count for the campaign segment builder, plus
420
+ a small sample so the UI can show who, not just how many."""
421
+ database = get_database(org_id, database_id)
422
+ rows = list_rows(org_id, database_id)
423
+ matched = apply_segment(rows, database["columns"], conditions)
424
+ return {"matched": len(matched), "sample": matched[:5]}
425
+
426
+
427
+ def add_row(org_id: str, actor_uid: str, database_id: str, values: dict) -> str:
428
+ orgs.require_permission(org_id, actor_uid, "edit_lists")
429
+ return insert_row(org_id, database_id, values)
430
+
431
+
432
+ def insert_row(org_id: str, database_id: str, values: dict) -> str:
433
+ """add_row without the role check — for callers that have already authorized the insert
434
+ some other way (backend/collect.py: a confirmed double opt-in, not a signed-in user)."""
435
+ get_database(org_id, database_id) # raises NotFoundError if missing
436
+ row_id = uuid.uuid4().hex
437
+ db.set_doc(_row_path(org_id, database_id, row_id), {"encrypted_data": encrypt(json.dumps(values))})
438
+ database = get_database(org_id, database_id)
439
+ db.update_doc(_database_path(org_id, database_id), {"row_count": database["row_count"] + 1})
440
+ known = {c["name"] for c in database["columns"]}
441
+ new_cols = [k for k in values if k not in known]
442
+ if new_cols:
443
+ updated_columns = database["columns"] + [{"name": k, "type": "text", "flagged_row_ids": []} for k in new_cols]
444
+ db.update_doc(_database_path(org_id, database_id), {"columns": updated_columns})
445
+ return row_id
446
+
447
+
448
+ def update_row(org_id: str, actor_uid: str, database_id: str, row_id: str, tags: dict) -> None:
449
+ """Merges `tags` into the row's existing values. Any key not already a known column is
450
+ appended to the database's column list (type "text") — a manually-added tag becomes a
451
+ real, placeholder-usable column for the whole database, matching how the CSV-derived
452
+ columns work, not a side channel."""
453
+ orgs.require_permission(org_id, actor_uid, "edit_lists")
454
+ path = _row_path(org_id, database_id, row_id)
455
+ doc = db.get_doc(path)
456
+ if doc is None:
457
+ raise orgs.NotFoundError(f"No row {row_id!r} in database {database_id!r}")
458
+ row = json.loads(decrypt(doc["encrypted_data"]))
459
+ row.update(tags)
460
+ db.set_doc(path, {"encrypted_data": encrypt(json.dumps(row))})
461
+
462
+ database = get_database(org_id, database_id)
463
+ known = {c["name"] for c in database["columns"]}
464
+ new_cols = [k for k in tags if k not in known]
465
+ if new_cols:
466
+ updated_columns = database["columns"] + [{"name": k, "type": "text", "flagged_row_ids": []} for k in new_cols]
467
+ db.update_doc(_database_path(org_id, database_id), {"columns": updated_columns})
468
+
469
+
470
+ def bulk_update_rows(org_id: str, actor_uid: str, database_id: str, row_ids: list[str], tags: dict) -> list[str]:
471
+ """Same merge semantics as update_row, applied to many rows in one call — the mass "fill a
472
+ column" / "add a tag to the selection" grid actions need this, since looping update_row
473
+ client-side would mean one HTTP round trip per selected row (unusable at a few thousand
474
+ rows). Fetches the database doc once up front and updates it once at the end, rather than
475
+ once per row like update_row does. Silently skips a row_id that no longer exists (e.g. a
476
+ stale selection from before a delete) instead of failing the whole batch over it."""
477
+ orgs.require_permission(org_id, actor_uid, "edit_lists")
478
+ database = get_database(org_id, database_id)
479
+
480
+ updated: list[str] = []
481
+ for row_id in row_ids:
482
+ path = _row_path(org_id, database_id, row_id)
483
+ doc = db.get_doc(path)
484
+ if doc is None:
485
+ continue
486
+ row = json.loads(decrypt(doc["encrypted_data"]))
487
+ row.update(tags)
488
+ db.set_doc(path, {"encrypted_data": encrypt(json.dumps(row))})
489
+ updated.append(row_id)
490
+
491
+ known = {c["name"] for c in database["columns"]}
492
+ new_cols = [k for k in tags if k not in known]
493
+ if new_cols:
494
+ updated_columns = database["columns"] + [{"name": k, "type": "text", "flagged_row_ids": []} for k in new_cols]
495
+ db.update_doc(_database_path(org_id, database_id), {"columns": updated_columns})
496
+
497
+ return updated
498
+
499
+
500
+ def bulk_append_tag(
501
+ org_id: str, actor_uid: str, database_id: str, row_ids: list[str], tag: str, tag_column: str = "Tags",
502
+ ) -> list[str]:
503
+ """Appends `tag` to the existing semicolon-delimited tag_column value for each row, rather
504
+ than overwriting it like bulk_update_rows does — each row keeps whatever tags it already
505
+ had, so this can't be expressed as one uniform PATCH value the way a column "fill" can.
506
+ Still a single HTTP call for the whole selection, looping server-side rather than once per
507
+ row over the network."""
508
+ orgs.require_permission(org_id, actor_uid, "edit_lists")
509
+ database = get_database(org_id, database_id)
510
+
511
+ updated: list[str] = []
512
+ for row_id in row_ids:
513
+ path = _row_path(org_id, database_id, row_id)
514
+ doc = db.get_doc(path)
515
+ if doc is None:
516
+ continue
517
+ row = json.loads(decrypt(doc["encrypted_data"]))
518
+ existing = [t for t in str(row.get(tag_column, "")).split(";") if t]
519
+ if tag not in existing:
520
+ existing.append(tag)
521
+ row[tag_column] = ";".join(existing)
522
+ db.set_doc(path, {"encrypted_data": encrypt(json.dumps(row))})
523
+ updated.append(row_id)
524
+
525
+ known = {c["name"] for c in database["columns"]}
526
+ if tag_column not in known:
527
+ updated_columns = database["columns"] + [{"name": tag_column, "type": "tag", "flagged_row_ids": []}]
528
+ db.update_doc(_database_path(org_id, database_id), {"columns": updated_columns})
529
+
530
+ return updated
531
+
532
+
533
+ def delete_rows(org_id: str, actor_uid: str, database_id: str, row_ids: list[str]) -> int:
534
+ """Bulk delete for the grid's mass-selection "Delete" action — same one-call-not-N
535
+ reasoning as bulk_update_rows. Returns the number actually deleted (stale ids are skipped,
536
+ not errors) so the caller can show an accurate count."""
537
+ orgs.require_permission(org_id, actor_uid, "edit_lists")
538
+ database = get_database(org_id, database_id)
539
+
540
+ deleted = 0
541
+ for row_id in row_ids:
542
+ path = _row_path(org_id, database_id, row_id)
543
+ if db.get_doc(path) is None:
544
+ continue
545
+ db.delete_doc(path)
546
+ deleted += 1
547
+
548
+ if deleted:
549
+ db.update_doc(_database_path(org_id, database_id), {"row_count": max(0, database["row_count"] - deleted)})
550
+
551
+ return deleted
552
+
553
+
554
+ def bulk_set_values(org_id: str, actor_uid: str, database_id: str, updates: dict[str, dict]) -> list[str]:
555
+ """Like bulk_update_rows, but each row gets its OWN value map rather than one uniform
556
+ value for everyone. This is what undoing a "fill column for N rows" needs — each row's
557
+ prior value was (generally) different before the fill overwrote it, so restoring them
558
+ can't be expressed as a single uniform PATCH the way the fill itself was."""
559
+ orgs.require_permission(org_id, actor_uid, "edit_lists")
560
+ database = get_database(org_id, database_id)
561
+
562
+ updated: list[str] = []
563
+ all_new_keys: set[str] = set()
564
+ for row_id, values in updates.items():
565
+ path = _row_path(org_id, database_id, row_id)
566
+ doc = db.get_doc(path)
567
+ if doc is None:
568
+ continue
569
+ row = json.loads(decrypt(doc["encrypted_data"]))
570
+ row.update(values)
571
+ db.set_doc(path, {"encrypted_data": encrypt(json.dumps(row))})
572
+ updated.append(row_id)
573
+ all_new_keys.update(values.keys())
574
+
575
+ known = {c["name"] for c in database["columns"]}
576
+ new_cols = [k for k in all_new_keys if k not in known]
577
+ if new_cols:
578
+ updated_columns = database["columns"] + [{"name": k, "type": "text", "flagged_row_ids": []} for k in new_cols]
579
+ db.update_doc(_database_path(org_id, database_id), {"columns": updated_columns})
580
+ return updated
581
+
582
+
583
+ def remove_column(org_id: str, actor_uid: str, database_id: str, column: str) -> dict:
584
+ """Drops a column from the schema and strips it from every row. Returns a snapshot
585
+ ({column def, values_by_row_id}) so the caller (the grid's undo stack) can restore it
586
+ exactly via restore_column without a second round trip to reconstruct what was deleted."""
587
+ orgs.require_permission(org_id, actor_uid, "edit_lists")
588
+ database = get_database(org_id, database_id)
589
+ col_def = next((c for c in database["columns"] if c["name"] == column), None)
590
+ if col_def is None:
591
+ raise orgs.NotFoundError(f"No column {column!r} in database {database_id!r}")
592
+
593
+ values_by_row_id: dict[str, str] = {}
594
+ for row in list_rows(org_id, database_id):
595
+ row_id = row["row_id"]
596
+ if column not in row:
597
+ continue
598
+ values_by_row_id[row_id] = row[column]
599
+ remaining = {k: v for k, v in row.items() if k not in (column, "row_id")}
600
+ db.set_doc(_row_path(org_id, database_id, row_id), {"encrypted_data": encrypt(json.dumps(remaining))})
601
+
602
+ updated_columns = [c for c in database["columns"] if c["name"] != column]
603
+ db.update_doc(_database_path(org_id, database_id), {"columns": updated_columns})
604
+ return {"column": col_def, "values_by_row_id": values_by_row_id}
605
+
606
+
607
+ def restore_column(org_id: str, actor_uid: str, database_id: str, column_def: dict, values_by_row_id: dict[str, str]) -> None:
608
+ """The inverse of remove_column — undo target for the grid's "Remove column" action."""
609
+ orgs.require_permission(org_id, actor_uid, "edit_lists")
610
+ database = get_database(org_id, database_id)
611
+ for row_id, value in values_by_row_id.items():
612
+ path = _row_path(org_id, database_id, row_id)
613
+ doc = db.get_doc(path)
614
+ if doc is None:
615
+ continue
616
+ row = json.loads(decrypt(doc["encrypted_data"]))
617
+ row[column_def["name"]] = value
618
+ db.set_doc(path, {"encrypted_data": encrypt(json.dumps(row))})
619
+ if not any(c["name"] == column_def["name"] for c in database["columns"]):
620
+ db.update_doc(_database_path(org_id, database_id), {"columns": database["columns"] + [column_def]})
621
+
622
+
623
+ def rename_column(org_id: str, actor_uid: str, database_id: str, column: str, new_name: str) -> str:
624
+ """Renames a column in the schema and re-keys it in every row, keeping column order. No
625
+ values change, so renaming back is an exact undo. Saved presets and campaigns that use
626
+ {OldName} keep the old text; the UI warns about that."""
627
+ orgs.require_permission(org_id, actor_uid, "edit_lists")
628
+ new_name = " ".join(new_name.split())
629
+ if not new_name:
630
+ raise ValidationError("A column name can't be empty")
631
+ if new_name == "row_id":
632
+ raise ValidationError("That name is reserved")
633
+ database = get_database(org_id, database_id)
634
+ if not any(c["name"] == column for c in database["columns"]):
635
+ raise orgs.NotFoundError(f"No column {column!r} in database {database_id!r}")
636
+ if new_name == column:
637
+ return new_name
638
+ if any(c["name"].lower() == new_name.lower() for c in database["columns"] if c["name"] != column):
639
+ raise ValidationError(f"There is already a column called {new_name!r}")
640
+
641
+ for row in list_rows(org_id, database_id):
642
+ if column not in row:
643
+ continue
644
+ rekeyed = {(new_name if k == column else k): v for k, v in row.items() if k != "row_id"}
645
+ db.set_doc(_row_path(org_id, database_id, row["row_id"]), {"encrypted_data": encrypt(json.dumps(rekeyed))})
646
+
647
+ updated_columns = [{**c, "name": new_name} if c["name"] == column else c for c in database["columns"]]
648
+ db.update_doc(_database_path(org_id, database_id), {"columns": updated_columns})
649
+ return new_name
650
+
651
+
652
+ def column_rename_suggestions(org_id: str, database_id: str) -> list[dict]:
653
+ from backend import rename_suggest
654
+
655
+ return rename_suggest.suggest_renames(get_database(org_id, database_id)["columns"])
656
+
657
+
658
+ def column_type_suggestions(org_id: str, database_id: str) -> list[dict]:
659
+ """Columns whose stored type no longer matches what their values say (e.g. a date column
660
+ that an older classifier called "contact"). Only ever a suggestion; never applied unasked.
661
+ Only recommends moving between the plain, low-stakes types, so a column the person
662
+ deliberately set to email, list or yes/no is left alone."""
663
+ database = get_database(org_id, database_id)
664
+ rows = list_rows(org_id, database_id)
665
+ suggestions = []
666
+ for col in database["columns"]:
667
+ if col["type"] not in ("text", "contact", "name"):
668
+ continue
669
+ guess = classify_column(col["name"], [r.get(col["name"], "") for r in rows])
670
+ if guess != col["type"] and guess in ("text", "date", "contact", "name", "email", "link", "bool"):
671
+ suggestions.append({"column": col["name"], "current": col["type"], "suggested": guess})
672
+ return suggestions
673
+
674
+
675
+ def rename_database(org_id: str, actor_uid: str, database_id: str, new_name: str) -> None:
676
+ orgs.require_permission(org_id, actor_uid, "edit_lists")
677
+ get_database(org_id, database_id)
678
+ if not new_name.strip():
679
+ raise ValidationError("Name can't be empty")
680
+ db.update_doc(_database_path(org_id, database_id), {"name": new_name.strip()})
681
+
682
+
683
+ def set_database_disabled(org_id: str, actor_uid: str, database_id: str, disabled: bool) -> None:
684
+ """"Disabled" means excluded from campaign sends only — still fully visible and editable
685
+ here. Doesn't cascade into blocking merges or anything else; that would be a separate,
686
+ more surprising rule than what the name implies."""
687
+ orgs.require_permission(org_id, actor_uid, "edit_lists")
688
+ get_database(org_id, database_id)
689
+ db.update_doc(_database_path(org_id, database_id), {"disabled": disabled})
690
+
691
+
692
+ def delete_database(org_id: str, actor_uid: str, database_id: str) -> None:
693
+ orgs.require_permission(org_id, actor_uid, "edit_lists")
694
+ get_database(org_id, database_id)
695
+ for path in list(db.query_prefix(_rows_prefix(org_id, database_id)).keys()):
696
+ db.delete_doc(path)
697
+ lookups_prefix = f"orgs/{org_id}/databases/{database_id}/lookups/"
698
+ for path in list(db.query_prefix(lookups_prefix).keys()):
699
+ db.delete_doc(path)
700
+ db.delete_doc(_database_path(org_id, database_id))
701
+
702
+
703
+ def duplicate_database(org_id: str, actor_uid: str, database_id: str, new_name: str) -> str:
704
+ orgs.require_permission(org_id, actor_uid, "edit_lists")
705
+ database = get_database(org_id, database_id)
706
+ rows = list_rows(org_id, database_id)
707
+ new_id = uuid.uuid4().hex
708
+ id_map = {r["row_id"]: uuid.uuid4().hex for r in rows}
709
+
710
+ db.set_doc(_database_path(org_id, new_id), {**database, "name": new_name, "created_at": _now()})
711
+ for r in rows:
712
+ payload = {k: v for k, v in r.items() if k != "row_id"}
713
+ db.set_doc(_row_path(org_id, new_id, id_map[r["row_id"]]), {"encrypted_data": encrypt(json.dumps(payload))})
714
+
715
+ lookups_prefix = f"orgs/{org_id}/databases/{database_id}/lookups/"
716
+ for path, data in db.query_prefix(lookups_prefix).items():
717
+ db.set_doc(_lookup_path(org_id, new_id, path[len(lookups_prefix):]), data)
718
+
719
+ # re-point flagged_row_ids at the new row ids — leaving them pointing at the OLD
720
+ # database's ids would silently flag the wrong rows (or none, once those ids never match).
721
+ updated_columns = [
722
+ {**c, "flagged_row_ids": [id_map[rid] for rid in c["flagged_row_ids"] if rid in id_map]}
723
+ for c in database["columns"]
724
+ ]
725
+ db.update_doc(_database_path(org_id, new_id), {"columns": updated_columns})
726
+ return new_id
727
+
728
+
729
+ def get_lookup_table(org_id: str, database_id: str, lookup_name: str) -> dict:
730
+ """Read-only access to a normalized lookup table's actual rows — the database doc only
731
+ ever stores the lookup's NAME and column list (see create_database_from_upload), never its
732
+ rows, so the grid's lookup-table viewer needs a dedicated fetch rather than reading it off
733
+ the database doc it already has."""
734
+ doc = db.get_doc(_lookup_path(org_id, database_id, lookup_name))
735
+ if doc is None:
736
+ raise orgs.NotFoundError(f"No lookup table {lookup_name!r} in database {database_id!r}")
737
+ return {"columns": doc["columns"], "rows": json.loads(decrypt(doc["encrypted_rows"]))}
738
+
739
+
740
+ def set_column_list(org_id: str, actor_uid: str, database_id: str, column: str, delimiter: str | None) -> None:
741
+ """Makes `column` a list column split on `delimiter` (or, with None, dismisses the
742
+ suggestion to do so and leaves the column as it is)."""
743
+ orgs.require_permission(org_id, actor_uid, "edit_lists")
744
+ if delimiter is not None and delimiter not in LIST_DELIMITERS:
745
+ raise ValidationError(f"Unknown list separator {delimiter!r}")
746
+ database = get_database(org_id, database_id)
747
+ if not any(c["name"] == column for c in database["columns"]):
748
+ raise orgs.NotFoundError(f"No column {column!r} in database {database_id!r}")
749
+ updated = []
750
+ for c in database["columns"]:
751
+ if c["name"] == column:
752
+ c = {k: v for k, v in c.items() if k != "list_suggestion"}
753
+ if delimiter is not None:
754
+ c = {**c, "type": "tag", "delimiter": delimiter, "flagged_row_ids": []}
755
+ updated.append(c)
756
+ db.update_doc(_database_path(org_id, database_id), {"columns": updated})
757
+
758
+
759
+ def update_column_type(org_id: str, database_id: str, column: str, new_type: str) -> list[str]:
760
+ if new_type not in COLUMN_TYPES:
761
+ raise ValidationError(f"Unknown column type {new_type!r}")
762
+ database = get_database(org_id, database_id)
763
+ if not any(c["name"] == column for c in database["columns"]):
764
+ raise orgs.NotFoundError(f"No column {column!r} in database {database_id!r}")
765
+
766
+ rows = list_rows(org_id, database_id)
767
+ values = [r.get(column, "") for r in rows]
768
+ if not _has_conforming_value(values, new_type):
769
+ raise ValidationError(
770
+ f"No existing value in {column!r} looks like a valid {new_type} — refusing the change"
771
+ )
772
+
773
+ flagged_indices = _flagged_values(values, new_type)
774
+ flagged_row_ids = [rows[i]["row_id"] for i in flagged_indices]
775
+
776
+ updated_columns = [
777
+ {**{k: v for k, v in c.items() if k != "list_suggestion"}, "type": new_type, "flagged_row_ids": flagged_row_ids,
778
+ **({"delimiter": c.get("delimiter") or ";"} if new_type == "tag" else {})}
779
+ if c["name"] == column else c
780
+ for c in database["columns"]
781
+ ]
782
+ db.update_doc(_database_path(org_id, database_id), {"columns": updated_columns})
783
+ return flagged_row_ids
784
+
785
+
786
+ def merge_databases(org_id: str, actor_uid: str, database_id_a: str, database_id_b: str, new_name: str) -> str:
787
+ """Concatenates both databases' rows under a brand-new database, reconciling columns by
788
+ name (union) and re-running classification + normalization over the combined set — a
789
+ merge isn't just a row concat, it's a fresh upload of the combined data."""
790
+ orgs.require_permission(org_id, actor_uid, "edit_lists")
791
+ rows_a = list_rows(org_id, database_id_a)
792
+ rows_b = list_rows(org_id, database_id_b)
793
+ headers = list(dict.fromkeys([k for r in rows_a + rows_b for k in r if k != "row_id"]))
794
+
795
+ # Exact-duplicate rows (e.g. the same contact present in both databases) are dropped
796
+ # before normalizing — besides being the obviously-wanted merge behavior on its own, an
797
+ # un-deduplicated duplicate row makes EVERY column pair look like a valid functional
798
+ # dependency (they trivially agree with their own duplicate), which would otherwise send
799
+ # the FD-discovery heuristic down a false trail.
800
+ seen_rows: set[tuple] = set()
801
+ combined: list[dict] = []
802
+ for r in rows_a + rows_b:
803
+ row = {h: r.get(h, "") for h in headers}
804
+ key = tuple(row[h] for h in headers)
805
+ if key in seen_rows:
806
+ continue
807
+ seen_rows.add(key)
808
+ combined.append(row)
809
+
810
+ column_types = {h: classify_column(h, [r[h] for r in combined]) for h in headers}
811
+ identity_columns = {h for h in headers if column_types[h] in ("email", "contact")}
812
+ result = normalize.normalize(combined, headers, exclude_determinants=identity_columns, auto_split=False)
813
+
814
+ database_id = uuid.uuid4().hex
815
+ id_rows = _assign_row_ids(result.root.rows)
816
+ columns = _columns_with_flags(column_types, result.root.columns, id_rows)
817
+
818
+ db.set_doc(_database_path(org_id, database_id), {
819
+ "name": new_name,
820
+ "source_filename": f"merge({database_id_a[:8]}, {database_id_b[:8]})",
821
+ "source_kind": "merge",
822
+ "created_at": _now(),
823
+ "row_count": len(result.root.rows),
824
+ "columns": columns,
825
+ "lookup_tables": [{"name": t.name, "columns": t.columns} for t in result.lookups],
826
+ "suggestions": result.suggestions,
827
+ })
828
+ for lookup in result.lookups:
829
+ db.set_doc(_lookup_path(org_id, database_id, lookup.name), {
830
+ "columns": lookup.columns,
831
+ "encrypted_rows": encrypt(json.dumps(lookup.rows)),
832
+ })
833
+ for row_id, row in id_rows:
834
+ db.set_doc(_row_path(org_id, database_id, row_id), {"encrypted_data": encrypt(json.dumps(row))})
835
+ return database_id
backend/delivery.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ What happened to a message after the mailbox's server accepted it.
3
+
4
+ SMTP only tells us the provider took the message. A provider may then hold it for an hour or more
5
+ (traffic, throttling) and a person reading "sent" cannot tell that from a lost message. The
6
+ mailbox's IMAP side shows what comes back: delay notices, bounce notices and replies. This module
7
+ reads those and records one state per recipient:
8
+
9
+ accepted The provider took it. Nothing has come back. This is all SMTP can prove.
10
+ delayed The provider (or the next server) says it is still trying.
11
+ bounced A failure notice came back for this message.
12
+ replied The person answered.
13
+
14
+ IMAP cannot prove a message reached an inbox, so nothing here says "delivered". After a day with
15
+ nothing reported, the screen says "no problems reported", which is what is actually known.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import email
21
+ import imaplib
22
+ import logging
23
+ import re
24
+ import ssl
25
+ from datetime import datetime, timedelta, timezone
26
+ from email import policy
27
+
28
+ from backend import firestore_client as db
29
+
30
+ log = logging.getLogger(__name__)
31
+
32
+ ACCEPTED, DELAYED, BOUNCED, REPLIED = "accepted", "delayed", "bounced", "replied"
33
+ # A later state replaces an earlier one; a bounce is never overwritten by a delay notice.
34
+ _RANK = {ACCEPTED: 0, DELAYED: 1, REPLIED: 2, BOUNCED: 3}
35
+
36
+ WATCH_DAYS = 3
37
+ RECHECK_MINUTES = 10
38
+ QUIET_AFTER_HOURS = 24
39
+ MAX_MESSAGES_READ = 400
40
+
41
+ IMAP_PORT = 993
42
+
43
+ _ID = re.compile(r"<([^<>\s]+)>")
44
+ _DELAY_WORDS = re.compile(r"delay|still trying|will keep trying|not yet delivered|warning", re.I)
45
+ _BOUNCE_WORDS = re.compile(r"undeliver|failure|failed|returned|bounce|could not be delivered|couldn't be delivered|rejected|no such user", re.I)
46
+ _BOUNCE_SENDERS = re.compile(r"mailer-daemon|postmaster|mail delivery", re.I)
47
+
48
+
49
+ def imap_details(credentials: dict) -> dict | None:
50
+ """The IMAP server and sign-in saved for a mailbox, or None when none was given.
51
+ The IMAP user and password default to the SMTP ones, which is usual for one mailbox."""
52
+ host = str(credentials.get("imap_host") or "").strip()
53
+ if not host:
54
+ return None
55
+ return {
56
+ "host": host,
57
+ "port": int(credentials.get("imap_port") or IMAP_PORT),
58
+ "username": str(credentials.get("imap_username") or credentials.get("username") or "").strip(),
59
+ "password": "".join(str(credentials.get("imap_password") or credentials.get("password") or "").split()),
60
+ }
61
+
62
+
63
+ def _ids_in(text: str) -> set[str]:
64
+ return {m.group(1) for m in _ID.finditer(text or "")}
65
+
66
+
67
+ def _text_of(msg) -> str:
68
+ """Every readable part of a notice, including the returned original, for finding our ids."""
69
+ out = []
70
+ for part in msg.walk():
71
+ if part.get_content_type() in ("message/rfc822", "text/rfc822-headers", "message/delivery-status"):
72
+ for sub in part.iter_parts() if part.is_multipart() else []:
73
+ out.append(str(sub))
74
+ elif part.get_content_maintype() == "text":
75
+ try:
76
+ out.append(part.get_content())
77
+ except (LookupError, UnicodeDecodeError):
78
+ payload = part.get_payload(decode=True) or b""
79
+ out.append(payload.decode("utf-8", errors="replace"))
80
+ return "\n".join(out)
81
+
82
+
83
+ def classify(raw: bytes, known_ids: set[str]) -> list[tuple[str, str]]:
84
+ """Reads one message from the mailbox and returns [(our message id, state)] for each of our
85
+ messages it is about. Ordinary mail that is about none of them returns []."""
86
+ try:
87
+ msg = email.message_from_bytes(raw, policy=policy.default)
88
+ except Exception: # a malformed message is skipped, never fatal
89
+ return []
90
+ subject = str(msg.get("Subject", ""))
91
+ sender = str(msg.get("From", ""))
92
+ notice = (
93
+ msg.get_content_type() == "multipart/report"
94
+ or bool(_BOUNCE_SENDERS.search(sender))
95
+ or bool(re.search(r"delivery status|undeliver|returned mail|failure notice", subject, re.I))
96
+ )
97
+ if notice:
98
+ body = _text_of(msg)
99
+ mentioned = _ids_in(body + "\n" + subject) & known_ids
100
+ if not mentioned:
101
+ return []
102
+ action = re.search(r"^Action:\s*(\w+)", body, re.I | re.M)
103
+ verdict = (action.group(1).lower() if action else "")
104
+ if verdict == "delayed":
105
+ state = DELAYED
106
+ elif verdict == "failed":
107
+ state = BOUNCED
108
+ elif _BOUNCE_WORDS.search(subject):
109
+ state = BOUNCED
110
+ elif _DELAY_WORDS.search(subject):
111
+ state = DELAYED
112
+ else:
113
+ state = BOUNCED
114
+ return [(mid, state) for mid in mentioned]
115
+
116
+ # Out-of-office and other automatic answers are not a person replying.
117
+ auto = str(msg.get("Auto-Submitted", "no")).lower()
118
+ if auto != "no" or str(msg.get("Precedence", "")).lower() in ("bulk", "junk", "auto_reply"):
119
+ return []
120
+ replied_to = _ids_in(str(msg.get("In-Reply-To", "")) + " " + str(msg.get("References", ""))) & known_ids
121
+ return [(mid, REPLIED) for mid in replied_to]
122
+
123
+
124
+ class ImapInbox:
125
+ """A short read-only visit to a mailbox's IMAP server."""
126
+
127
+ def __init__(self, details: dict):
128
+ self._imap = imaplib.IMAP4_SSL(details["host"], details["port"], ssl_context=ssl.create_default_context(), timeout=20)
129
+ self._imap.login(details["username"], details["password"])
130
+
131
+ def recent(self, since: datetime, limit: int = MAX_MESSAGES_READ) -> list[bytes]:
132
+ """Raw messages that arrived since `since`, newest first, from the inbox and junk folders."""
133
+ out: list[bytes] = []
134
+ for folder in self._folders():
135
+ status, _ = self._imap.select(f'"{folder}"', readonly=True)
136
+ if status != "OK":
137
+ continue
138
+ status, data = self._imap.search(None, "SINCE", since.strftime("%d-%b-%Y"))
139
+ if status != "OK" or not data or not data[0]:
140
+ continue
141
+ for num in reversed(data[0].split()[-limit:]):
142
+ status, parts = self._imap.fetch(num, "(BODY.PEEK[])")
143
+ if status == "OK" and parts and isinstance(parts[0], tuple):
144
+ out.append(parts[0][1])
145
+ if len(out) >= limit:
146
+ return out
147
+ return out
148
+
149
+ def _folders(self) -> list[str]:
150
+ names = ["INBOX"]
151
+ status, lines = self._imap.list()
152
+ if status == "OK":
153
+ for line in lines or []:
154
+ text = line.decode(errors="replace") if isinstance(line, bytes) else str(line)
155
+ if "\\junk" in text.lower():
156
+ name = text.rsplit(' "', 1)[-1].strip('"') if ' "' in text else text.split()[-1]
157
+ names.append(name.strip('"'))
158
+ return names
159
+
160
+ def close(self) -> None:
161
+ try:
162
+ self._imap.logout()
163
+ except (imaplib.IMAP4.error, OSError):
164
+ pass
165
+
166
+
167
+ def open_inbox(details: dict) -> ImapInbox:
168
+ """Separate so tests can stand in for a mailbox."""
169
+ return ImapInbox(details)
170
+
171
+
172
+ def _watch_path(org_id: str, send_id: str) -> str:
173
+ return f"watch_sends/{org_id}__{send_id}"
174
+
175
+
176
+ def watch(org_id: str, send_id: str) -> None:
177
+ """Asks for this send's recipients to be checked for a few days."""
178
+ until = (datetime.now(timezone.utc) + timedelta(days=WATCH_DAYS)).isoformat()
179
+ db.set_doc(_watch_path(org_id, send_id), {"org_id": org_id, "send_id": send_id, "until": until})
180
+
181
+
182
+ def shown_state(record: dict, now: datetime | None = None, tracking: bool = True) -> dict:
183
+ """What to show for one recipient: {state, label, note}. `tracking` is False when the mailbox
184
+ has no IMAP details, which is said plainly instead of implying all is well."""
185
+ now = now or datetime.now(timezone.utc)
186
+ status = record.get("status")
187
+ if status != "sent":
188
+ return {"state": status, "label": None, "note": None}
189
+ state = record.get("delivery") or ACCEPTED
190
+ if state == BOUNCED:
191
+ return {"state": state, "label": "Bounced", "note": record.get("delivery_note") or "The receiving server sent it back."}
192
+ if state == REPLIED:
193
+ return {"state": state, "label": "Replied", "note": None}
194
+ if state == DELAYED:
195
+ return {"state": state, "label": "Delayed at your provider", "note": "Your provider or the receiving server is still trying. This is not an error."}
196
+ if not tracking:
197
+ return {"state": state, "label": "Accepted by your provider", "note": "Add the IMAP details to this mailbox to see delays, bounces and replies."}
198
+ try:
199
+ age = now - datetime.fromisoformat(record.get("at"))
200
+ except (TypeError, ValueError):
201
+ age = timedelta(0)
202
+ if age >= timedelta(hours=QUIET_AFTER_HOURS) and record.get("delivery_checked"):
203
+ return {"state": state, "label": "Accepted, no problems reported", "note": None}
204
+ return {"state": state, "label": "Accepted by your provider", "note": "Providers sometimes hold mail for an hour or more before passing it on."}
205
+
206
+
207
+ def check_send(org_id: str, send_id: str, now: datetime | None = None) -> dict:
208
+ """Reads the mailbox's IMAP side once and updates each recipient of this send. Returns
209
+ {checked, bounced, delayed, replied, reason}. Never raises for a mailbox problem."""
210
+ from backend import mailboxes, sending # imported here: both import this module's neighbours
211
+
212
+ now = now or datetime.now(timezone.utc)
213
+ send = sending.get_send(org_id, send_id)
214
+ records = send.get("per_recipient") or {}
215
+ wanted = {r["reference"].strip("<>"): row_id for row_id, r in records.items() if r.get("status") == "sent" and r.get("reference")}
216
+ result = {"checked": False, "bounced": 0, "delayed": 0, "replied": 0, "reason": ""}
217
+ if not wanted:
218
+ result["reason"] = "nothing_to_check"
219
+ return result
220
+ try:
221
+ credentials = mailboxes.get_decrypted_credentials(org_id, send["mailbox_connection_id"])
222
+ except Exception:
223
+ result["reason"] = "mailbox_missing"
224
+ return result
225
+ details = imap_details(credentials)
226
+ if details is None:
227
+ result["reason"] = "imap_missing"
228
+ return result
229
+ try:
230
+ started = min(datetime.fromisoformat(r["at"]) for r in records.values() if r.get("at"))
231
+ except ValueError:
232
+ started = now - timedelta(days=1)
233
+ inbox = None
234
+ try:
235
+ inbox = open_inbox(details)
236
+ raws = inbox.recent(started - timedelta(days=1))
237
+ except (imaplib.IMAP4.error, OSError) as exc:
238
+ log.info("IMAP check failed for %s: %r", send_id, exc)
239
+ result["reason"] = "imap_failed"
240
+ return result
241
+ finally:
242
+ if inbox is not None:
243
+ inbox.close()
244
+
245
+ found: dict[str, str] = {}
246
+ for raw in raws:
247
+ for mid, state in classify(raw, set(wanted)):
248
+ if _RANK[state] > _RANK.get(found.get(mid, ACCEPTED), 0):
249
+ found[mid] = state
250
+ stamp = now.isoformat()
251
+ for mid, row_id in wanted.items():
252
+ record = dict(records[row_id])
253
+ record["delivery_checked"] = stamp
254
+ state = found.get(mid)
255
+ if state and _RANK[state] >= _RANK.get(record.get("delivery") or ACCEPTED, 0):
256
+ record["delivery"] = state
257
+ record["delivery_at"] = stamp
258
+ result[state] = result.get(state, 0) + 1
259
+ records[row_id] = record
260
+ db.update_doc(f"orgs/{org_id}/sends/{send_id}", {"per_recipient": records})
261
+ result["checked"] = True
262
+ return result
263
+
264
+
265
+ def run_due(now: datetime | None = None, budget_seconds: float = 60) -> dict:
266
+ """Checks watched sends that have not been looked at for a few minutes. Real mailboxes only."""
267
+ import time
268
+
269
+ from backend import mailer_client # here: mailer_client imports the SMTP mailer, which imports this module
270
+
271
+ if not mailer_client.real_send_enabled():
272
+ return {"checked": 0}
273
+ now = now or datetime.now(timezone.utc)
274
+ started = time.monotonic()
275
+ done = 0
276
+ for path, doc in list(db.query_prefix("watch_sends/").items()):
277
+ if time.monotonic() - started > budget_seconds:
278
+ break
279
+ if datetime.fromisoformat(doc["until"]) < now:
280
+ db.delete_doc(path)
281
+ continue
282
+ last = doc.get("last_check")
283
+ if last and now - datetime.fromisoformat(last) < timedelta(minutes=RECHECK_MINUTES):
284
+ continue
285
+ try:
286
+ check_send(doc["org_id"], doc["send_id"], now)
287
+ except Exception: # one bad send must not stop the rest
288
+ log.exception("Delivery check failed for %s", doc.get("send_id"))
289
+ db.update_doc(path, {"last_check": now.isoformat()})
290
+ done += 1
291
+ return {"checked": done}
backend/dns_check.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Looks up a domain's email records (SPF, DKIM, DMARC, MX) so Settings > Advanced can say
3
+ what is already set up instead of only describing it.
4
+
5
+ Uses a public DNS-over-HTTPS resolver, so it needs no extra library. DKIM records live
6
+ under a "selector" name chosen by the mail provider; there is no way to list them, so the
7
+ common selectors are tried and "not found" only means none of those exist.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import re
14
+ import urllib.parse
15
+ import urllib.request
16
+
17
+ _RESOLVER = "https://dns.google/resolve"
18
+ _DOMAIN = re.compile(r"^(?=.{3,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$")
19
+ DKIM_SELECTORS = ("default", "google", "selector1", "selector2", "k1", "k2", "mail", "dkim", "s1", "s2", "x", "zoho", "mx")
20
+
21
+
22
+ def _lookup(name: str, rtype: str) -> list[str]:
23
+ url = f"{_RESOLVER}?{urllib.parse.urlencode({'name': name, 'type': rtype})}"
24
+ with urllib.request.urlopen(url, timeout=6) as resp: # noqa: S310 — fixed https resolver
25
+ data = json.load(resp)
26
+ return [a["data"].strip('"').replace('" "', "") for a in data.get("Answer", []) if a.get("type") in (1, 5, 15, 16)]
27
+
28
+
29
+ def check_domain(domain: str, lookup=_lookup) -> dict:
30
+ """{domain, spf, dkim, dmarc, mx}. Each item is {ok, value, note}; ok is None when
31
+ the lookup itself failed (no answer either way)."""
32
+ domain = (domain or "").strip().lower()
33
+ if not _DOMAIN.match(domain):
34
+ raise ValueError("Enter a domain like yourcompany.com")
35
+
36
+ def safe(name: str, rtype: str) -> list[str] | None:
37
+ try:
38
+ return lookup(name, rtype)
39
+ except Exception: # noqa: BLE001 — network trouble is reported, not raised
40
+ return None
41
+
42
+ result: dict = {"domain": domain}
43
+ txt = safe(domain, "TXT")
44
+ spf = [t for t in txt or [] if t.lower().startswith("v=spf1")]
45
+ result["spf"] = (
46
+ {"ok": None, "value": "", "note": "We couldn't look this up. Try again."} if txt is None
47
+ else {"ok": len(spf) == 1, "value": spf[0] if spf else "",
48
+ "note": "Found." if len(spf) == 1 else "More than one SPF record. Mail servers need exactly one." if spf else "No SPF record."}
49
+ )
50
+ dmarc_txt = safe(f"_dmarc.{domain}", "TXT")
51
+ dmarc = [t for t in dmarc_txt or [] if t.lower().startswith("v=dmarc1")]
52
+ result["dmarc"] = (
53
+ {"ok": None, "value": "", "note": "We couldn't look this up. Try again."} if dmarc_txt is None
54
+ else {"ok": bool(dmarc), "value": dmarc[0] if dmarc else "", "note": "Found." if dmarc else "No DMARC record."}
55
+ )
56
+ found = None
57
+ for selector in DKIM_SELECTORS:
58
+ records = safe(f"{selector}._domainkey.{domain}", "TXT") or []
59
+ if any("p=" in r for r in records):
60
+ found = selector
61
+ break
62
+ result["dkim"] = (
63
+ {"ok": True, "value": f"{found}._domainkey", "note": f"Found under the name {found}."} if found
64
+ else {"ok": False, "value": "", "note": "Not found under the usual names. Your provider may use another name; check with them."}
65
+ )
66
+ mx = safe(domain, "MX")
67
+ result["mx"] = (
68
+ {"ok": None, "value": "", "note": "We couldn't look this up. Try again."} if mx is None
69
+ else {"ok": bool(mx), "value": ", ".join(mx[:3]), "note": "Found." if mx else "No mail servers listed, so replies can't arrive."}
70
+ )
71
+ return result
backend/email_parts.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The parts of an email beyond its HTML: files attached to every copy, and images the sender
3
+ uploaded into the message itself.
4
+
5
+ Uploaded images arrive in the HTML as data: URIs, which Gmail and most clients refuse to show.
6
+ extract_inline_images swaps each one for a cid: reference and returns the image bytes, so the
7
+ mailer can send them as inline parts of the same message. No image hosting is needed.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import base64
13
+ import binascii
14
+ import re
15
+ from dataclasses import dataclass
16
+
17
+ MAX_ATTACHMENTS = 10
18
+ MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024
19
+ MAX_TOTAL_ATTACHMENT_BYTES = 20 * 1024 * 1024
20
+ MAX_INLINE_IMAGES = 20
21
+
22
+ _DATA_URI_RE = re.compile(
23
+ r"""(src\s*=\s*["'])data:image/(png|jpe?g|gif|webp);base64,([A-Za-z0-9+/=\s]+)(["'])""",
24
+ re.IGNORECASE,
25
+ )
26
+ _UNSAFE_FILENAME_RE = re.compile(r'[\\/:*?"<>|\r\n\t]+')
27
+
28
+
29
+ @dataclass
30
+ class Attachment:
31
+ filename: str
32
+ content_type: str
33
+ data: bytes
34
+
35
+
36
+ @dataclass
37
+ class InlineImage:
38
+ cid: str
39
+ subtype: str
40
+ data: bytes
41
+
42
+
43
+ def safe_filename(name: str, fallback: str = "file") -> str:
44
+ cleaned = _UNSAFE_FILENAME_RE.sub(" ", name).strip(" .")
45
+ return cleaned[:150] or fallback
46
+
47
+
48
+ def decode_attachments(items: list[dict] | None) -> list[Attachment]:
49
+ """Turns the request's [{filename, content_type, data_b64}] into Attachments, enforcing the
50
+ count and size limits. Raises ValueError with a message the sender can act on."""
51
+ if not items:
52
+ return []
53
+ if len(items) > MAX_ATTACHMENTS:
54
+ raise ValueError(f"Attach at most {MAX_ATTACHMENTS} files")
55
+ out: list[Attachment] = []
56
+ total = 0
57
+ for item in items:
58
+ filename = safe_filename(str(item.get("filename") or ""), "attachment")
59
+ try:
60
+ data = base64.b64decode(item.get("data_b64") or "", validate=True)
61
+ except (binascii.Error, ValueError) as exc:
62
+ raise ValueError(f"{filename} could not be read") from exc
63
+ if not data:
64
+ raise ValueError(f"{filename} is empty")
65
+ if len(data) > MAX_ATTACHMENT_BYTES:
66
+ raise ValueError(f"{filename} is larger than 10 MB")
67
+ total += len(data)
68
+ content_type = str(item.get("content_type") or "application/octet-stream")
69
+ if "/" not in content_type:
70
+ content_type = "application/octet-stream"
71
+ out.append(Attachment(filename=filename, content_type=content_type, data=data))
72
+ if total > MAX_TOTAL_ATTACHMENT_BYTES:
73
+ raise ValueError("Attachments add up to more than 20 MB")
74
+ return out
75
+
76
+
77
+ def extract_inline_images(html: str) -> tuple[str, list[InlineImage]]:
78
+ """Replaces every data:image src in `html` with a cid: reference. Identical images share one
79
+ part. Raises ValueError when there are too many, so a send never silently drops one."""
80
+ images: list[InlineImage] = []
81
+ seen: dict[str, str] = {}
82
+
83
+ def swap(m: re.Match) -> str:
84
+ payload = re.sub(r"\s+", "", m.group(3))
85
+ cid = seen.get(payload)
86
+ if cid is None:
87
+ try:
88
+ data = base64.b64decode(payload, validate=True)
89
+ except (binascii.Error, ValueError):
90
+ return m.group(0)
91
+ cid = f"m8img{len(images) + 1}@m8ion"
92
+ subtype = m.group(2).lower().replace("jpg", "jpeg")
93
+ images.append(InlineImage(cid=cid, subtype=subtype, data=data))
94
+ seen[payload] = cid
95
+ return f"{m.group(1)}cid:{cid}{m.group(4)}"
96
+
97
+ out = _DATA_URI_RE.sub(swap, html)
98
+ if len(images) > MAX_INLINE_IMAGES:
99
+ raise ValueError(f"Use at most {MAX_INLINE_IMAGES} images in one message")
100
+ return out, images
backend/firebase_app.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Single shared firebase_admin App instance. backend/firestore_client.py (real Firestore
3
+ branch) and backend/auth.py (real token verification) both use this instead of each
4
+ initializing their own — firebase_admin.initialize_app() raises if called twice for the
5
+ same app name, so this is a real requirement, not just tidiness.
6
+
7
+ Only imported/called when LOCAL_MODE=false or REAL_AUTH_ENABLED=true — never during the
8
+ test suite (backend/tests/conftest.py forces both off), so tests never need real credentials.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import os
15
+ import re
16
+
17
+ import firebase_admin
18
+ from firebase_admin import credentials
19
+
20
+ _app: firebase_admin.App | None = None
21
+
22
+ _PEM_HEAD = "-----BEGIN PRIVATE KEY-----"
23
+ _PEM_TAIL = "-----END PRIVATE KEY-----"
24
+ _PEM = re.compile(r"-----BEGIN\s*PRIVATE\s*KEY-----(.*?)-----END\s*PRIVATE\s*KEY-----", re.S)
25
+
26
+
27
+ def service_account_info(raw: str) -> dict:
28
+ """
29
+ Reads the key from the text of FIREBASE_SERVICE_ACCOUNT_JSON. Pasting a key into a host's
30
+ secret box often damages the line breaks inside "private_key" (they become the two characters
31
+ \\n, or spaces), and the key then cannot be read at all. Repair that here instead of failing.
32
+ """
33
+ text = raw.strip()
34
+ if len(text) > 1 and text[0] == text[-1] and text[0] in "'\"":
35
+ text = text[1:-1]
36
+ info = json.loads(text, strict=False)
37
+ key = str(info.get("private_key", "")).replace("\\n", "\n")
38
+ # Rebuild the key from its body. The header may have lost its spaces too
39
+ # ("-----BEGINPRIVATEKEY-----") when every space was stripped from the pasted text.
40
+ found = _PEM.search(key)
41
+ if found:
42
+ body = "".join(found.group(1).split())
43
+ lines = [body[i:i + 64] for i in range(0, len(body), 64)]
44
+ key = "\n".join([_PEM_HEAD, *lines, _PEM_TAIL]) + "\n"
45
+ info["private_key"] = key
46
+ return info
47
+
48
+
49
+ def get_app() -> firebase_admin.App:
50
+ global _app
51
+ if _app is None:
52
+ # A host that only offers environment variables (the Hugging Face Space) passes the key's
53
+ # content in FIREBASE_SERVICE_ACCOUNT_JSON; a developer's machine points at the file.
54
+ key_json = os.getenv("FIREBASE_SERVICE_ACCOUNT_JSON", "").strip()
55
+ if key_json:
56
+ cred = credentials.Certificate(service_account_info(key_json))
57
+ else:
58
+ cred = credentials.Certificate(
59
+ os.getenv("GOOGLE_APPLICATION_CREDENTIALS", "./secrets/firebase-service-account.dev.json")
60
+ )
61
+ _app = firebase_admin.initialize_app(cred)
62
+ return _app
backend/firestore_client.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The single seam between the org/role model (and everything else that stores operational
3
+ metadata) and its actual backing store. Every caller uses get_doc/set_doc/update_doc/
4
+ delete_doc/query_prefix from THIS module, never backend.local_store or the real Firestore
5
+ client directly.
6
+
7
+ LOCAL_MODE governs which backing store this module uses — real Firestore (a real GCP
8
+ project + service-account credential now exist, see backend/firebase_app.py) when false,
9
+ the local SQLite shim when true (the default in tests — see tests/conftest.py, which forces
10
+ LOCAL_MODE=true regardless of .env so the suite never touches real Firestore).
11
+
12
+ Firestore's own Python client accepts the same slash-delimited path strings our path scheme
13
+ already uses (`db.document("orgs/abc123")`, `db.collection("orgs/abc123/mailboxes")`) — no
14
+ translation layer needed between our path convention and Firestore's.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from firebase_admin import firestore
20
+
21
+ from backend import local_store
22
+ from backend.firebase_app import get_app
23
+ from backend.local_mode import LOCAL_MODE
24
+
25
+
26
+ def _db():
27
+ get_app()
28
+ return firestore.client()
29
+
30
+
31
+ def get_doc(path: str) -> dict | None:
32
+ if LOCAL_MODE:
33
+ return local_store.get_doc(path)
34
+ snap = _db().document(path).get()
35
+ return snap.to_dict() if snap.exists else None
36
+
37
+
38
+ def set_doc(path: str, data: dict) -> None:
39
+ if LOCAL_MODE:
40
+ local_store.set_doc(path, data)
41
+ return
42
+ _db().document(path).set(data)
43
+
44
+
45
+ def update_doc(path: str, partial: dict) -> dict:
46
+ """Shared across both backends: read-modify-write via this module's own get_doc/
47
+ set_doc, so the merge semantics (raise if the doc doesn't exist) stay identical
48
+ regardless of which store is active — no need to duplicate the logic per backend."""
49
+ existing = get_doc(path)
50
+ if existing is None:
51
+ raise KeyError(f"No document at {path!r} to update")
52
+ existing.update(partial)
53
+ set_doc(path, existing)
54
+ return existing
55
+
56
+
57
+ def delete_doc(path: str) -> None:
58
+ if LOCAL_MODE:
59
+ local_store.delete_doc(path)
60
+ return
61
+ _db().document(path).delete()
62
+
63
+
64
+ def query_prefix(prefix: str) -> dict[str, dict]:
65
+ """All documents under a collection path (e.g. "orgs/abc123/mailboxes/"), keyed by
66
+ their full path — matches local_store.query_prefix's contract exactly."""
67
+ if LOCAL_MODE:
68
+ return local_store.query_prefix(prefix)
69
+ collection_path = prefix.rstrip("/")
70
+ docs = _db().collection(collection_path).stream()
71
+ return {f"{collection_path}/{doc.id}": doc.to_dict() for doc in docs}
backend/fonts/DejaVuSans-Bold.ttf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b184b89e3c1075f22f6b71575b6fc20d4972b3cfd3b23322ca6fd596dcaef167
3
+ size 704128
backend/fonts/DejaVuSans.ttf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3fdf69cabf06049ea70a00b5919340e2ce1e6d02b0cc3c4b44fb6801bd1e0d22
3
+ size 756072
backend/fonts/DejaVuSerif.ttf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:107244956e9962b9e96faccdc551825e0ae0898ae13737133e1b921a2fd35ffa
3
+ size 379740
backend/fonts/IMFellEnglishSC-Regular.ttf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bfcbaf94bafb9843518e55034449b6c7f796cef0b3f6c36985c2eb1cde7b55e0
3
+ size 180328
backend/fonts/LICENSE_DEJAVU.txt ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
2
+ Glyphs imported from Arev fonts are (c) Tavmjong Bah (see below)
3
+
4
+ Bitstream Vera Fonts Copyright
5
+ ------------------------------
6
+
7
+ Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is
8
+ a trademark of Bitstream, Inc.
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of the fonts accompanying this license ("Fonts") and associated
12
+ documentation files (the "Font Software"), to reproduce and distribute the
13
+ Font Software, including without limitation the rights to use, copy, merge,
14
+ publish, distribute, and/or sell copies of the Font Software, and to permit
15
+ persons to whom the Font Software is furnished to do so, subject to the
16
+ following conditions:
17
+
18
+ The above copyright and trademark notices and this permission notice shall
19
+ be included in all copies of one or more of the Font Software typefaces.
20
+
21
+ The Font Software may be modified, altered, or added to, and in particular
22
+ the designs of glyphs or characters in the Fonts may be modified and
23
+ additional glyphs or characters may be added to the Fonts, only if the fonts
24
+ are renamed to names not containing either the words "Bitstream" or the word
25
+ "Vera".
26
+
27
+ This License becomes null and void to the extent applicable to Fonts or Font
28
+ Software that has been modified and is distributed under the "Bitstream
29
+ Vera" names.
30
+
31
+ The Font Software may be sold as part of a larger software package but no
32
+ copy of one or more of the Font Software typefaces may be sold by itself.
33
+
34
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
35
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
36
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
37
+ TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
38
+ FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING
39
+ ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
40
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
41
+ THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE
42
+ FONT SOFTWARE.
43
+
44
+ Except as contained in this notice, the names of Gnome, the Gnome
45
+ Foundation, and Bitstream Inc., shall not be used in advertising or
46
+ otherwise to promote the sale, use or other dealings in this Font Software
47
+ without prior written authorization from the Gnome Foundation or Bitstream
48
+ Inc., respectively. For further information, contact: fonts at gnome dot
49
+ org.
50
+
51
+ Arev Fonts Copyright
52
+ ------------------------------
53
+
54
+ Copyright (c) 2006 by Tavmjong Bah. All Rights Reserved.
55
+
56
+ Permission is hereby granted, free of charge, to any person obtaining
57
+ a copy of the fonts accompanying this license ("Fonts") and
58
+ associated documentation files (the "Font Software"), to reproduce
59
+ and distribute the modifications to the Bitstream Vera Font Software,
60
+ including without limitation the rights to use, copy, merge, publish,
61
+ distribute, and/or sell copies of the Font Software, and to permit
62
+ persons to whom the Font Software is furnished to do so, subject to
63
+ the following conditions:
64
+
65
+ The above copyright and trademark notices and this permission notice
66
+ shall be included in all copies of one or more of the Font Software
67
+ typefaces.
68
+
69
+ The Font Software may be modified, altered, or added to, and in
70
+ particular the designs of glyphs or characters in the Fonts may be
71
+ modified and additional glyphs or characters may be added to the
72
+ Fonts, only if the fonts are renamed to names not containing either
73
+ the words "Tavmjong Bah" or the word "Arev".
74
+
75
+ This License becomes null and void to the extent applicable to Fonts
76
+ or Font Software that has been modified and is distributed under the
77
+ "Tavmjong Bah Arev" names.
78
+
79
+ The Font Software may be sold as part of a larger software package but
80
+ no copy of one or more of the Font Software typefaces may be sold by
81
+ itself.
82
+
83
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
84
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
85
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
86
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL
87
+ TAVMJONG BAH BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
88
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
89
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
90
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
91
+ OTHER DEALINGS IN THE FONT SOFTWARE.
92
+
93
+ Except as contained in this notice, the name of Tavmjong Bah shall not
94
+ be used in advertising or otherwise to promote the sale, use or other
95
+ dealings in this Font Software without prior written authorization
96
+ from Tavmjong Bah. For further information, contact: tavmjong @ free
97
+ . fr.
98
+
99
+ $Id: LICENSE 2133 2007-11-28 02:46:28Z lechimp $
backend/fonts/README.md ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Certificate fonts
2
+
3
+ Fonts a certificate's name can be drawn in (backend/certificates.py). The same files are served
4
+ to the browser from frontend/public/fonts so the drag-to-place view matches what is generated.
5
+
6
+ | File | Licence |
7
+ |---|---|
8
+ | DejaVuSans.ttf, DejaVuSans-Bold.ttf, DejaVuSerif.ttf | Bitstream Vera / DejaVu licence (LICENSE_DEJAVU.txt), free to redistribute |
9
+ | IMFellEnglishSC-Regular.ttf | SIL Open Font License 1.1 (IM Fell types, Igino Marini) |
10
+
11
+ A sender can also upload their own .ttf or .otf for one campaign; it is used only for that send.
backend/identity.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Identity check (KYC), level 1: the recommended fields from docs/product/account-types.md section 6.
2
+
3
+ Stored at identity/{uid}. A submission is "submitted" until a person on our side reviews it; nothing
4
+ here verifies anything or gates any action yet. ID numbers and uploads are not collected at this level.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from datetime import datetime, timezone
11
+
12
+ from backend import accounts
13
+ from backend import firestore_client as db
14
+
15
+ # (key, label, required) in the order they are shown.
16
+ FIELDS = {
17
+ accounts.ORGANIZATION: [
18
+ ("legal_name", "Legal name", True),
19
+ ("trading_name", "Trading name", False),
20
+ ("registration_number", "Registration number (RC)", True),
21
+ ("country", "Country of registration", True),
22
+ ("address", "Registered address", True),
23
+ ("business_type", "Business type", True),
24
+ ("contact_name", "Contact person", True),
25
+ ("contact_role", "Their role", True),
26
+ ("contact_phone", "Their phone", True),
27
+ ("website", "Website or social page", True),
28
+ ],
29
+ accounts.INDIVIDUAL: [
30
+ ("legal_name", "Legal name", True),
31
+ ("date_of_birth", "Date of birth", True),
32
+ ("phone", "Phone", True),
33
+ ("address", "Home or work address", True),
34
+ ("occupation", "What you send mail for", False),
35
+ ("website", "Website or social page", False),
36
+ ],
37
+ }
38
+
39
+
40
+ # Filled in by the map picker alongside country and address; kept if present, never required.
41
+ PHONE_KEYS = ("phone", "contact_phone")
42
+ PLACE_EXTRAS = ("state", "lga", "postal_code")
43
+
44
+
45
+ def _path(uid: str) -> str:
46
+ return f"identity/{uid}"
47
+
48
+
49
+ def overall_status(account_type: str, review: dict) -> str:
50
+ """approved: every required detail verified. needs_changes: one is rejected. Else submitted."""
51
+ required = [k for k, _l, req in FIELDS[account_type] if req]
52
+ if any(r.get("decision") == "rejected" for r in review.values()):
53
+ return "needs_changes"
54
+ if required and all(review.get(k, {}).get("decision") == "verified" for k in required):
55
+ return "approved"
56
+ return "submitted"
57
+
58
+
59
+ def describe(uid: str) -> dict:
60
+ account_type = accounts.account_type_of(uid)
61
+ if not account_type:
62
+ raise accounts.AccountError("Choose an account type first")
63
+ doc = db.get_doc(_path(uid)) or {}
64
+ return {
65
+ "status": doc.get("status", "not_started"),
66
+ "values": doc.get("values", {}),
67
+ "submitted_at": doc.get("submitted_at"),
68
+ "review": doc.get("review", {}),
69
+ "fields": [{"key": k, "label": l, "required": r} for k, l, r in FIELDS[account_type]],
70
+ }
71
+
72
+
73
+ def status_of(uid: str) -> str:
74
+ return (db.get_doc(_path(uid)) or {}).get("status", "not_started")
75
+
76
+
77
+ def submit(uid: str, values: dict) -> dict:
78
+ account_type = accounts.account_type_of(uid)
79
+ if not account_type:
80
+ raise accounts.AccountError("Choose an account type first")
81
+ clean: dict[str, str] = {}
82
+ for key, label, required in FIELDS[account_type]:
83
+ value = str(values.get(key) or "").strip()[:300]
84
+ if required and not value:
85
+ raise accounts.AccountError(f"{label} is needed")
86
+ if key in PHONE_KEYS and value and not re.fullmatch(r"\+\d{1,4} \d{6,14}", value):
87
+ raise accounts.AccountError(f"{label} should be a calling code and digits only")
88
+ if value:
89
+ clean[key] = value
90
+ if clean.get("country") == "Nigeria":
91
+ rc = clean.get("registration_number")
92
+ if rc and not re.fullmatch(r"(?i)(RC|BN|IT|LP|LLP)\s?-?\s?\d{4,8}", rc):
93
+ raise accounts.AccountError("Registration number should look like RC1234567")
94
+ code = str(values.get("postal_code") or "").strip()
95
+ if code and not re.fullmatch(r"\d{6}", code):
96
+ raise accounts.AccountError("Postal code should be 6 digits")
97
+ for key in PLACE_EXTRAS:
98
+ value = str(values.get(key) or "").strip()[:300]
99
+ if value:
100
+ clean[key] = value
101
+ # A detail that did not change keeps its review; a changed or new one is looked at afresh.
102
+ old = db.get_doc(_path(uid)) or {}
103
+ review = {k: r for k, r in old.get("review", {}).items() if old.get("values", {}).get(k) == clean.get(k)}
104
+ db.set_doc(_path(uid), {"status": overall_status(account_type, review), "values": clean, "review": review,
105
+ "submitted_at": datetime.now(timezone.utc).isoformat()})
106
+ return describe(uid)
backend/invites.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Invite links: someone who can manage the team invites an email address to a role; the
3
+ person opens the link, signs in or signs up with that address, and joins.
4
+
5
+ Firestore layout:
6
+ orgs/{org_id}/invites/{token} — {email, role, invited_by, created_at, expires_at, status}
7
+ invite_tokens/{token} — {org_id} (so a link can be opened without knowing the org)
8
+
9
+ Status is "pending", "accepted" or "revoked". An invite past expires_at can't be used.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import html
15
+ import re
16
+ import secrets
17
+ from datetime import datetime, timedelta, timezone
18
+
19
+ from backend import firestore_client as db
20
+ from backend import mailboxes, mailer_client, orgs, settings
21
+ from backend.core.constants import INVITE_TTL_DAYS
22
+
23
+ _EMAIL = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
24
+
25
+
26
+ def _now() -> datetime:
27
+ return datetime.now(timezone.utc)
28
+
29
+
30
+ def _path(org_id: str, token: str) -> str:
31
+ return f"orgs/{org_id}/invites/{token}"
32
+
33
+
34
+ def _expired(invite: dict) -> bool:
35
+ return datetime.fromisoformat(invite["expires_at"]) <= _now()
36
+
37
+
38
+ def create_invite(org_id: str, actor_uid: str, email: str, role: str) -> dict:
39
+ email = (email or "").strip().lower()
40
+ if not _EMAIL.match(email):
41
+ raise ValueError("Enter a valid email address")
42
+ orgs._check_grant(org_id, actor_uid, role)
43
+ if any(m.get("email", "").lower() == email for m in orgs.list_members(org_id).values()):
44
+ raise ValueError(f"{email} is already in this organisation")
45
+ for token, existing in _pending(org_id).items():
46
+ if existing["email"] == email:
47
+ revoke_invite(org_id, actor_uid, token)
48
+ token = secrets.token_urlsafe(24)
49
+ invite = {
50
+ "email": email,
51
+ "role": role,
52
+ "invited_by": actor_uid,
53
+ "created_at": _now().isoformat(),
54
+ "expires_at": (_now() + timedelta(days=INVITE_TTL_DAYS)).isoformat(),
55
+ "status": "pending",
56
+ }
57
+ db.set_doc(_path(org_id, token), invite)
58
+ db.set_doc(f"invite_tokens/{token}", {"org_id": org_id})
59
+ return {"token": token, **invite}
60
+
61
+
62
+ def _pending(org_id: str) -> dict[str, dict]:
63
+ prefix = f"orgs/{org_id}/invites/"
64
+ return {
65
+ path[len(prefix):]: data
66
+ for path, data in db.query_prefix(prefix).items()
67
+ if data["status"] == "pending" and not _expired(data)
68
+ }
69
+
70
+
71
+ def list_invites(org_id: str, actor_uid: str) -> list[dict]:
72
+ orgs.require_permission(org_id, actor_uid, "manage_team")
73
+ return sorted(({"token": t, **d} for t, d in _pending(org_id).items()), key=lambda d: d["created_at"])
74
+
75
+
76
+ def revoke_invite(org_id: str, actor_uid: str, token: str) -> None:
77
+ orgs.require_permission(org_id, actor_uid, "manage_team")
78
+ invite = db.get_doc(_path(org_id, token))
79
+ if invite is None:
80
+ raise orgs.NotFoundError("No such invite")
81
+ invite["status"] = "revoked"
82
+ db.set_doc(_path(org_id, token), invite)
83
+
84
+
85
+ def _lookup(token: str) -> tuple[str, dict]:
86
+ index = db.get_doc(f"invite_tokens/{token}")
87
+ invite = db.get_doc(_path(index["org_id"], token)) if index else None
88
+ if invite is None:
89
+ raise orgs.NotFoundError("This invite link isn't valid")
90
+ return index["org_id"], invite
91
+
92
+
93
+ def describe(token: str) -> dict:
94
+ """What the invite page shows before the person accepts."""
95
+ org_id, invite = _lookup(token)
96
+ role_name = next((r["name"] for r in orgs.list_roles(org_id) if r["key"] == invite["role"]), invite["role"])
97
+ state = invite["status"] if invite["status"] != "pending" else ("expired" if _expired(invite) else "pending")
98
+ return {
99
+ "org_id": org_id,
100
+ "org_name": orgs.get_org(org_id)["name"],
101
+ "email": invite["email"],
102
+ "role": invite["role"],
103
+ "role_name": role_name,
104
+ "status": state,
105
+ "expires_at": invite["expires_at"],
106
+ }
107
+
108
+
109
+ def accept(token: str, uid: str, email: str) -> str:
110
+ """Joins uid to the invite's org. The signed-in address must be the invited one.
111
+ Returns the org_id."""
112
+ org_id, invite = _lookup(token)
113
+ if invite["status"] != "pending":
114
+ raise ValueError(f"This invite has been {invite['status']}")
115
+ if _expired(invite):
116
+ raise ValueError("This invite has expired. Ask for a new one.")
117
+ if (email or "").strip().lower() != invite["email"]:
118
+ raise orgs.PermissionError_(f"This invite is for {invite['email']}. Sign in with that address to accept it.")
119
+ orgs.join(org_id, uid, invite["role"], invite["email"])
120
+ invite["status"] = "accepted"
121
+ invite["accepted_by"] = uid
122
+ db.set_doc(_path(org_id, token), invite)
123
+ return org_id
124
+
125
+
126
+ def send_invite_email(org_id: str, invite: dict, link: str, inviter: str) -> bool:
127
+ """Best effort: sends the link from the org's default (or first) verified mailbox.
128
+ Returns False when there is no mailbox to send from or the send fails; the link can
129
+ still be copied and shared by hand."""
130
+ boxes = {cid: m for cid, m in mailboxes.list_mailboxes(org_id).items() if m.get("status") == "verified"}
131
+ if not boxes:
132
+ return False
133
+ preferred = settings.email_settings(org_id)["default_mailbox_id"]
134
+ cid = preferred if preferred in boxes else next(iter(boxes))
135
+ org_name = orgs.get_org(org_id)["name"]
136
+ role_name = next((r["name"] for r in orgs.list_roles(org_id) if r["key"] == invite["role"]), invite["role"])
137
+ org_html, role_html, inviter_html = (html.escape(v) for v in (org_name, role_name, inviter or "Someone"))
138
+ body = (
139
+ f"<p>{inviter_html} invited you to join <strong>{org_html}</strong> on M8ion as {role_html}.</p>"
140
+ f'<p><a href="{html.escape(link)}">Accept the invite</a></p>'
141
+ f"<p>The link works for {INVITE_TTL_DAYS} days. Sign in or sign up with this address ({invite['email']}).</p>"
142
+ )
143
+ try:
144
+ mailer = mailer_client.get_mailer(boxes[cid]["kind"], mailboxes.get_decrypted_credentials(org_id, cid))
145
+ try:
146
+ mailer.send(to_addr=invite["email"], subject=f"Join {org_name} on M8ion", body=body)
147
+ finally:
148
+ close = getattr(mailer, "close", None)
149
+ if close:
150
+ close()
151
+ except Exception: # noqa: BLE001 — a failed courtesy email must not fail the invite
152
+ return False
153
+ return True
backend/local_mode.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LOCAL_MODE gates every real-external-service call in the backend behind a local,
3
+ zero-provisioning substitute — same principle as the prior single-operator build's
4
+ local dev path (see the archived README in ../M8ion-archived-2026-09-23.zip for the
5
+ original rationale), rebuilt fresh for the org/role model.
6
+
7
+ Defaults to true: no real GCP/Firebase project has been provisioned yet (see
8
+ docs/blueprint/blueprint.md and the Phase 0 brainstorm — billing isn't enabled), so
9
+ local-only is the only mode that currently works. Flip to false in .env once a real
10
+ Firebase project exists and backend/firestore_client.py's real branch is implemented.
11
+ """
12
+
13
+ import os
14
+
15
+ LOCAL_MODE = os.getenv("LOCAL_MODE", "true").lower() == "true"
backend/local_store.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A local, SQLite-backed stand-in for Firestore's document-path model: one generic table,
3
+ keyed by a slash-delimited path (e.g. "orgs/abc123" or "orgs/abc123/members/uid1"), value
4
+ is a JSON blob. Enough to build and test the org/role model with zero external services.
5
+
6
+ Not a full Firestore emulator — no query engine, no transactions across paths. Just get /
7
+ set / update / delete by exact path, plus a prefix scan for "list documents under this
8
+ collection", which is all the org/role model needs. See backend/firestore_client.py for the
9
+ seam that swaps this out for the real Firebase Admin SDK once a GCP project exists.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import sqlite3
16
+ import threading
17
+ from contextlib import closing
18
+ from pathlib import Path
19
+
20
+ _DEFAULT_DB_PATH = "local_store.db"
21
+ _lock = threading.Lock()
22
+ _db_path = _DEFAULT_DB_PATH
23
+
24
+
25
+ def init_local_store(db_path: str | None = None) -> None:
26
+ """(Re)point the store at a given SQLite file and ensure its table exists. Call this
27
+ once at process/test startup — every other function in this module uses whatever
28
+ path was set here last."""
29
+ global _db_path
30
+ _db_path = db_path or _DEFAULT_DB_PATH
31
+ with closing(_connect()) as conn:
32
+ with conn:
33
+ conn.execute(
34
+ "CREATE TABLE IF NOT EXISTS firestore_docs (path TEXT PRIMARY KEY, data TEXT NOT NULL)"
35
+ )
36
+
37
+
38
+ def _connect() -> sqlite3.Connection:
39
+ parent = Path(_db_path).parent
40
+ if str(parent) not in ("", "."):
41
+ parent.mkdir(parents=True, exist_ok=True)
42
+ return sqlite3.connect(_db_path)
43
+
44
+
45
+ def get_doc(path: str) -> dict | None:
46
+ with _lock, closing(_connect()) as conn:
47
+ row = conn.execute("SELECT data FROM firestore_docs WHERE path = ?", (path,)).fetchone()
48
+ return json.loads(row[0]) if row else None
49
+
50
+
51
+ def set_doc(path: str, data: dict) -> None:
52
+ with _lock, closing(_connect()) as conn:
53
+ with conn:
54
+ conn.execute(
55
+ "INSERT INTO firestore_docs (path, data) VALUES (?, ?) "
56
+ "ON CONFLICT(path) DO UPDATE SET data = excluded.data",
57
+ (path, json.dumps(data)),
58
+ )
59
+
60
+
61
+ def update_doc(path: str, partial: dict) -> dict:
62
+ """Merge partial into the existing doc (shallow merge, Firestore .update() semantics
63
+ for top-level fields). Raises if the doc doesn't exist — matches Firestore behavior."""
64
+ existing = get_doc(path)
65
+ if existing is None:
66
+ raise KeyError(f"No document at {path!r} to update")
67
+ existing.update(partial)
68
+ set_doc(path, existing)
69
+ return existing
70
+
71
+
72
+ def delete_doc(path: str) -> None:
73
+ with _lock, closing(_connect()) as conn:
74
+ with conn:
75
+ conn.execute("DELETE FROM firestore_docs WHERE path = ?", (path,))
76
+
77
+
78
+ def query_prefix(prefix: str) -> dict[str, dict]:
79
+ """Direct children of `prefix` only (a collection path, e.g. "orgs/abc123/members/"),
80
+ keyed by their full path — matches real Firestore's .collection().stream() semantics,
81
+ which never reaches into a deeper nested subcollection. A naive string-prefix match would
82
+ also catch e.g. "orgs/x/databases/db1/rows/row1" when listing "orgs/x/databases/", which
83
+ real Firestore's collection() never would, so the remainder past the prefix is required
84
+ to contain no further "/"."""
85
+ like_pattern = f"{prefix}%"
86
+ with _lock, closing(_connect()) as conn:
87
+ rows = conn.execute(
88
+ "SELECT path, data FROM firestore_docs WHERE path LIKE ?", (like_pattern,)
89
+ ).fetchall()
90
+ return {
91
+ path: json.loads(data)
92
+ for path, data in rows
93
+ if "/" not in path[len(prefix):]
94
+ }
backend/mailboxes.py ADDED
@@ -0,0 +1,402 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Mailbox connections — the relay identity an org sends through (docs/blueprint/adr/0001).
3
+ Two kinds, both stored the same way once connected: "oauth" (Gmail/Outlook/Yahoo — see
4
+ backend/core/constants.py SUPPORTED_OAUTH_PROVIDERS) and "smtp" (hosting-provider mailboxes,
5
+ raw host/port/username/password). Credentials are encrypted at rest via backend.crypto_utils
6
+ (the prototype stand-in for ADR-0002's GCP KMS envelope encryption).
7
+
8
+ Verification is the 3-OTP round-trip from SRS FR-6: send unique OTPs from the connected
9
+ mailbox to M8ion's own test mailbox, then confirm receipt/content/metadata match before the
10
+ connection is usable for real sends. The five failure states below are SRS FR-7, verbatim.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import imaplib
16
+ import json
17
+ import re
18
+ import uuid
19
+ from datetime import datetime, timedelta, timezone
20
+
21
+ from backend import delivery
22
+ from backend import firestore_client as db
23
+ from backend import mailer_client
24
+ from backend import orgs
25
+ from backend.core.constants import (
26
+ MAILBOX_CREDENTIAL_CHANGE_DAYS,
27
+ MAILBOX_DAILY_LIMIT_MAX,
28
+ SYSTEM_SENDER_ADDRESS_PROTO,
29
+ SYSTEM_TEST_MAILBOX_ADDRESS_PROTO,
30
+ SUPPORTED_OAUTH_PROVIDERS,
31
+ VERIFICATION_OTP_COUNT,
32
+ )
33
+ from backend.crypto_utils import decrypt, encrypt
34
+ from backend.mock_mailer import AuthError, ConnectionFailure, MockInbox, MockMailer
35
+
36
+ # Stands in for "M8ion's own test mailbox" until a real domain/inbox exists — used for the
37
+ # mock round-trip (REAL_SEND_ENABLED=false). The real round-trip (true) has no inbox to
38
+ # read back yet (that needs IMAP, unbuilt — see _verify_real's docstring), so it sends to
39
+ # SYSTEM_SENDER_ADDRESS_PROTO instead, the one real mailbox this project actually holds.
40
+ SYSTEM_TEST_INBOX = MockInbox()
41
+
42
+ # SRS FR-7, worded exactly as specified.
43
+ FAILURE_MESSAGES = {
44
+ "auth_rejected": "We couldn't sign in to that mailbox. Double-check the email and password, then try again.",
45
+ "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.",
46
+ "silent_failure": "We couldn't verify delivery. Contact support and we'll help you troubleshoot.",
47
+ "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.",
48
+ "content_mismatch": "Something didn't match during verification. This connection has been flagged for manual review.",
49
+ "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.",
50
+ }
51
+
52
+ # Honest scope for the real (non-mocked) path: auth + send are genuinely verified;
53
+ # arrival isn't, since reading a real inbox back needs IMAP (Phase 2, unbuilt).
54
+ VERIFIED_REAL_MESSAGE = (
55
+ "Your credentials were accepted and a test message was sent through your mail server. "
56
+ "We can't yet confirm it arrived — check the inbox yourself for full certainty."
57
+ )
58
+
59
+
60
+ SEND_FAILED_MESSAGE = (
61
+ "We signed in to that mailbox, but your provider refused the test message. "
62
+ "Check that sending is allowed for this account, then try again."
63
+ )
64
+
65
+
66
+ class ValidationError(Exception):
67
+ pass
68
+
69
+
70
+ def _now() -> str:
71
+ return datetime.now(timezone.utc).isoformat()
72
+
73
+
74
+ def _connection_path(org_id: str, connection_id: str) -> str:
75
+ return f"orgs/{org_id}/mailboxes/{connection_id}"
76
+
77
+
78
+ def connect_mailbox(org_id: str, actor_uid: str, kind: str, credentials: dict) -> str:
79
+ """Registers a new, not-yet-verified mailbox connection. An org can have more than one
80
+ (SRS FR-5). Requires admin or owner (SRS: mailbox management is an org-management
81
+ action, not a day-to-day sending one)."""
82
+ orgs.require_permission(org_id, actor_uid, "manage_mailboxes")
83
+
84
+ if kind == "oauth":
85
+ provider = credentials.get("provider")
86
+ if provider not in SUPPORTED_OAUTH_PROVIDERS:
87
+ raise ValidationError(f"Unsupported OAuth provider {provider!r}")
88
+ elif kind == "smtp":
89
+ required = {"host", "port", "username", "password"}
90
+ missing = required - credentials.keys()
91
+ if missing:
92
+ raise ValidationError(f"SMTP connection missing fields: {missing}")
93
+ credentials = _clean_imap(credentials, required=True)
94
+ # Spaces in an app password are display grouping, never part of it.
95
+ credentials = {**credentials, "password": "".join(str(credentials["password"]).split())}
96
+ else:
97
+ raise ValidationError(f"Unknown mailbox kind {kind!r}")
98
+
99
+ # The sending address isn't a secret — it's the From: on every message this connection
100
+ # sends — so it's kept plain alongside the encrypted blob rather than requiring a
101
+ # decrypt just to list connections (SRS FR-5's list view needs this on every load).
102
+ email = credentials.get("username") if kind == "smtp" else credentials.get("email")
103
+
104
+ connection_id = uuid.uuid4().hex
105
+ db.set_doc(
106
+ _connection_path(org_id, connection_id),
107
+ {
108
+ "kind": kind,
109
+ "email": email,
110
+ "has_imap": bool(credentials.get("imap_host")),
111
+ "encrypted_credentials": encrypt(json.dumps(credentials)),
112
+ "status": "pending_verification",
113
+ "status_message": None,
114
+ "created_at": _now(),
115
+ "verified_at": None,
116
+ },
117
+ )
118
+ return connection_id
119
+
120
+
121
+ def _clean_imap(credentials: dict, required: bool) -> dict:
122
+ """Checks the incoming (IMAP) half of an SMTP mailbox. Both halves are needed: SMTP sends,
123
+ IMAP reads back what the provider did with the message (delays, bounces, replies). The IMAP
124
+ user and password may be left out when they are the same as the SMTP ones."""
125
+ host = str(credentials.get("imap_host") or "").strip()
126
+ if not host:
127
+ if required:
128
+ raise ValidationError("Add the incoming (IMAP) server too. M8ion needs it to show delays, bounces and replies.")
129
+ return credentials
130
+ try:
131
+ port = int(credentials.get("imap_port") or 993)
132
+ except (TypeError, ValueError) as exc:
133
+ raise ValidationError("The IMAP port must be a number, usually 993") from exc
134
+ if not 1 <= port <= 65535:
135
+ raise ValidationError("The IMAP port must be a number, usually 993")
136
+ cleaned = {**credentials, "imap_host": host, "imap_port": port}
137
+ for key in ("imap_username", "imap_password"):
138
+ if not str(cleaned.get(key) or "").strip():
139
+ cleaned.pop(key, None)
140
+ if cleaned.get("imap_password"):
141
+ cleaned["imap_password"] = "".join(str(cleaned["imap_password"]).split())
142
+ return cleaned
143
+
144
+
145
+ def get_mailbox(org_id: str, connection_id: str) -> dict:
146
+ doc = db.get_doc(_connection_path(org_id, connection_id))
147
+ if doc is None:
148
+ raise orgs.NotFoundError(f"No mailbox connection {connection_id!r} for org {org_id!r}")
149
+ return doc
150
+
151
+
152
+ def list_mailboxes(org_id: str) -> dict[str, dict]:
153
+ prefix = f"orgs/{org_id}/mailboxes/"
154
+ docs = db.query_prefix(prefix)
155
+ return {path[len(prefix):]: data for path, data in docs.items()}
156
+
157
+
158
+ def set_dismissed(org_id: str, actor_uid: str, connection_id: str, dismissed: bool) -> None:
159
+ """Hides (or restores) a failed try from the Mailboxes page and the attention counts. The
160
+ connection itself is kept, so this is fully reversible."""
161
+ orgs.require_permission(org_id, actor_uid, "manage_mailboxes")
162
+ connection = get_mailbox(org_id, connection_id)
163
+ if dismissed and connection.get("status") in ("verified", "pending_verification"):
164
+ raise ValidationError("Only a mailbox that did not connect can be dismissed")
165
+ db.update_doc(_connection_path(org_id, connection_id), {"dismissed": dismissed})
166
+
167
+
168
+ # Per-mailbox choices. Empty / None means "use the organisation's setting".
169
+ DEFAULT_MAILBOX_SETTINGS = {"label": "", "from_name": "", "reply_to": "", "daily_limit": 0, "save_sent_copy": None}
170
+ _EMAIL = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
171
+
172
+
173
+ def mailbox_settings(connection: dict) -> dict:
174
+ return DEFAULT_MAILBOX_SETTINGS | {k: v for k, v in (connection.get("settings") or {}).items() if k in DEFAULT_MAILBOX_SETTINGS}
175
+
176
+
177
+ def update_settings(org_id: str, actor_uid: str, connection_id: str, values: dict) -> dict:
178
+ """Saves this mailbox's own sender name, reply-to, daily limit, Sent-copy choice and label."""
179
+ orgs.require_permission(org_id, actor_uid, "manage_mailboxes")
180
+ connection = get_mailbox(org_id, connection_id)
181
+ unknown = set(values) - set(DEFAULT_MAILBOX_SETTINGS)
182
+ if unknown:
183
+ raise ValidationError(f"Unknown setting: {', '.join(sorted(unknown))}")
184
+ merged = mailbox_settings(connection) | values
185
+ for key in ("label", "from_name"):
186
+ merged[key] = " ".join(str(merged[key] or "").split())
187
+ if len(merged[key]) > 80:
188
+ raise ValidationError("Keep names to 80 characters or fewer")
189
+ merged["reply_to"] = str(merged["reply_to"] or "").strip()
190
+ if merged["reply_to"] and not _EMAIL.match(merged["reply_to"]):
191
+ raise ValidationError("Replies address doesn't look like an email address")
192
+ try:
193
+ merged["daily_limit"] = int(merged["daily_limit"] or 0)
194
+ except (TypeError, ValueError) as exc:
195
+ raise ValidationError("Daily limit must be a whole number") from exc
196
+ if not 0 <= merged["daily_limit"] <= MAILBOX_DAILY_LIMIT_MAX:
197
+ raise ValidationError(f"Daily limit must be between 0 (no limit) and {MAILBOX_DAILY_LIMIT_MAX:,}")
198
+ if merged["save_sent_copy"] is not None:
199
+ merged["save_sent_copy"] = bool(merged["save_sent_copy"])
200
+ db.update_doc(_connection_path(org_id, connection_id), {"settings": merged})
201
+ return merged
202
+
203
+
204
+ def next_credential_change(connection: dict) -> str | None:
205
+ """When the sign-in details may next be changed, or None if they may be changed now."""
206
+ last = connection.get("credentials_changed_at")
207
+ if not last:
208
+ return None
209
+ allowed = datetime.fromisoformat(last) + timedelta(days=MAILBOX_CREDENTIAL_CHANGE_DAYS)
210
+ return allowed.isoformat() if allowed > datetime.now(timezone.utc) else None
211
+
212
+
213
+ def change_credentials(org_id: str, actor_uid: str, connection_id: str, credentials: dict) -> dict:
214
+ """Replaces an SMTP mailbox's server and sign-in details, at most once every
215
+ MAILBOX_CREDENTIAL_CHANGE_DAYS. The new details are tested first; if the test fails
216
+ the old ones stay in place and the change doesn't count. Returns
217
+ {status, status_message, changed}."""
218
+ orgs.require_permission(org_id, actor_uid, "manage_mailboxes")
219
+ connection = get_mailbox(org_id, connection_id)
220
+ if connection["kind"] != "smtp":
221
+ raise ValidationError("Only mailboxes connected with server details can be changed here")
222
+ wait = next_credential_change(connection)
223
+ # Adding the incoming (IMAP) side to a mailbox that has none is allowed at any time: it only
224
+ # turns on delivery tracking and does not touch how the mailbox signs in to send.
225
+ adding_imap = not connection.get("has_imap") and bool(credentials) and all(k.startswith("imap_") for k in credentials)
226
+ if wait and not adding_imap:
227
+ raise ValidationError(f"These details were changed recently. They can be changed again from {wait[:10]}.")
228
+ current = _decrypted_credentials(connection)
229
+ merged = {**current, **{k: v for k, v in credentials.items() if v not in (None, "")}}
230
+ missing = {"host", "port", "username", "password"} - merged.keys()
231
+ if missing:
232
+ raise ValidationError(f"SMTP connection missing fields: {missing}")
233
+ merged["password"] = "".join(str(merged["password"]).split())
234
+ merged = _clean_imap(merged, required=False)
235
+ if merged == current:
236
+ raise ValidationError("Nothing changed")
237
+
238
+ path = _connection_path(org_id, connection_id)
239
+ if adding_imap:
240
+ # Only the incoming side is new: test just that. Re-sending the test emails would be slow
241
+ # and is not needed, since sending is unchanged.
242
+ if mailer_client.real_send_enabled():
243
+ details = delivery.imap_details(merged)
244
+ try:
245
+ delivery.open_inbox(details).close()
246
+ except (imaplib.IMAP4.error, OSError):
247
+ return {"status": "imap_failed", "status_message": FAILURE_MESSAGES["imap_failed"], "changed": False}
248
+ db.update_doc(path, {"has_imap": True, "encrypted_credentials": encrypt(json.dumps(merged))})
249
+ return {"status": connection.get("status"), "status_message": connection.get("status_message"), "changed": True}
250
+ keep = {k: connection.get(k) for k in ("email", "has_imap", "encrypted_credentials", "status", "status_message", "verified_at")}
251
+ db.update_doc(path, {"email": merged["username"], "has_imap": bool(merged.get("imap_host")), "encrypted_credentials": encrypt(json.dumps(merged)), "status": "pending_verification"})
252
+ status = verify_mailbox(org_id, connection_id)
253
+ if status != "verified":
254
+ message = get_mailbox(org_id, connection_id).get("status_message")
255
+ db.update_doc(path, keep)
256
+ return {"status": status, "status_message": message, "changed": False}
257
+ if not adding_imap:
258
+ db.update_doc(path, {"credentials_changed_at": _now()})
259
+ return {"status": status, "status_message": get_mailbox(org_id, connection_id).get("status_message"), "changed": True}
260
+
261
+
262
+ def remove_mailbox(org_id: str, actor_uid: str, connection_id: str) -> None:
263
+ """Deletes the connection and its stored sign-in details. Past sends keep their record.
264
+ Refused while a sign-up form sends its confirmation emails through it."""
265
+ orgs.require_permission(org_id, actor_uid, "manage_mailboxes")
266
+ get_mailbox(org_id, connection_id)
267
+ users = [
268
+ data.get("name") or "a sign-up form"
269
+ for data in db.query_prefix(f"orgs/{org_id}/collect_keys/").values()
270
+ if not data.get("revoked") and data.get("mailbox_connection_id") == connection_id
271
+ ]
272
+ if users:
273
+ raise ValidationError(f"{users[0]} sends its confirmation emails from this mailbox. Pick another mailbox there first.")
274
+ db.delete_doc(_connection_path(org_id, connection_id))
275
+ for path, brand in db.query_prefix(f"orgs/{org_id}/brands/").items():
276
+ if connection_id in brand.get("mailbox_ids", []):
277
+ db.update_doc(path, {"mailbox_ids": [i for i in brand["mailbox_ids"] if i != connection_id]})
278
+ emails_path = f"orgs/{org_id}/settings/emails"
279
+ prefs = db.get_doc(emails_path)
280
+ if prefs and prefs.get("default_mailbox_id") == connection_id:
281
+ db.set_doc(emails_path, {**prefs, "default_mailbox_id": ""})
282
+
283
+
284
+ def get_decrypted_credentials(org_id: str, connection_id: str) -> dict:
285
+ """The only sanctioned way to read a connection's plaintext credentials — callers
286
+ outside this module should never touch encrypted_credentials directly."""
287
+ return _decrypted_credentials(get_mailbox(org_id, connection_id))
288
+
289
+
290
+ def _decrypted_credentials(connection: dict) -> dict:
291
+ return json.loads(decrypt(connection["encrypted_credentials"]))
292
+
293
+
294
+ def verify_mailbox(org_id: str, connection_id: str) -> str:
295
+ """Runs the verification round-trip and updates the connection's status. Returns the
296
+ final status string. Never raises for an expected failure mode — those are all
297
+ recorded as a status, per SRS FR-7 ("robust support", not a bare exception).
298
+
299
+ Branches on mailer_client.real_send_enabled(): mocked (default) runs the full 5-state
300
+ round-trip against an in-memory inbox; real runs _verify_real, which can only reach
301
+ 3 of those 5 states — see its docstring for exactly why."""
302
+ connection = get_mailbox(org_id, connection_id)
303
+ credentials = _decrypted_credentials(connection)
304
+
305
+ if mailer_client.real_send_enabled():
306
+ return _verify_real(org_id, connection_id, connection["kind"], credentials)
307
+ return _verify_mock(org_id, connection_id, credentials)
308
+
309
+
310
+ def _verify_mock(org_id: str, connection_id: str, credentials: dict) -> str:
311
+ try:
312
+ mailer = MockMailer(credentials, SYSTEM_TEST_INBOX)
313
+ except AuthError:
314
+ return _settle(org_id, connection_id, "auth_rejected")
315
+ except ConnectionFailure:
316
+ return _settle(org_id, connection_id, "connection_failed")
317
+
318
+ otps = [uuid.uuid4().hex[:8] for _ in range(VERIFICATION_OTP_COUNT)]
319
+ for i, otp in enumerate(otps):
320
+ mailer.send(
321
+ to_addr=SYSTEM_TEST_MAILBOX_ADDRESS_PROTO,
322
+ subject=f"M8ion verification {connection_id} #{i}",
323
+ body=f"OTP:{otp}",
324
+ )
325
+
326
+ arrived = [
327
+ m for m in SYSTEM_TEST_INBOX.messages_to(SYSTEM_TEST_MAILBOX_ADDRESS_PROTO)
328
+ if connection_id in m.subject
329
+ ]
330
+
331
+ if not arrived:
332
+ return _settle(org_id, connection_id, "silent_failure")
333
+
334
+ if len(arrived) < len(otps):
335
+ _delete_test_messages(arrived)
336
+ return _settle(org_id, connection_id, "unreliable")
337
+
338
+ expected_bodies = {f"OTP:{otp}" for otp in otps}
339
+ arrived_bodies = {m.body for m in arrived}
340
+ if arrived_bodies != expected_bodies:
341
+ _delete_test_messages(arrived)
342
+ return _settle(org_id, connection_id, "content_mismatch")
343
+
344
+ _delete_test_messages(arrived)
345
+ return _settle(org_id, connection_id, "verified")
346
+
347
+
348
+ def _verify_real(org_id: str, connection_id: str, kind: str, credentials: dict) -> str:
349
+ """Real SMTP auth + a real send attempt against SYSTEM_SENDER_ADDRESS_PROTO — the one
350
+ real mailbox this project holds credentials for. Can only ever reach "auth_rejected",
351
+ "connection_failed", or "verified" — "silent_failure"/"unreliable"/"content_mismatch"
352
+ all require reading the destination inbox back (IMAP) to detect, which isn't built
353
+ (Phase 2's bounce-detection work). A "verified" here means auth + send succeeded, not
354
+ that arrival was confirmed — VERIFIED_REAL_MESSAGE says so explicitly in the UI."""
355
+ try:
356
+ mailer = mailer_client.get_mailer(kind, credentials)
357
+ except AuthError:
358
+ return _settle(org_id, connection_id, "auth_rejected")
359
+ except (ConnectionFailure, NotImplementedError):
360
+ return _settle(org_id, connection_id, "connection_failed")
361
+
362
+ try:
363
+ for i in range(VERIFICATION_OTP_COUNT):
364
+ otp = uuid.uuid4().hex[:8]
365
+ mailer.send(
366
+ to_addr=SYSTEM_SENDER_ADDRESS_PROTO,
367
+ subject=f"M8ion verification {connection_id} #{i}",
368
+ body=f"OTP:{otp}",
369
+ )
370
+ except (AuthError, ConnectionFailure):
371
+ # Sign-in already worked, so telling the person the server was unreachable would be wrong.
372
+ return _settle(org_id, connection_id, "connection_failed", message_override=SEND_FAILED_MESSAGE)
373
+
374
+ details = delivery.imap_details(credentials)
375
+ if details is not None:
376
+ try:
377
+ delivery.open_inbox(details).close()
378
+ except (imaplib.IMAP4.error, OSError):
379
+ return _settle(org_id, connection_id, "imap_failed")
380
+ return _settle(org_id, connection_id, "verified", message_override=VERIFIED_REAL_MESSAGE)
381
+
382
+
383
+ def _delete_test_messages(messages) -> None:
384
+ """The test mailbox doesn't keep verification OTPs around once a round-trip is
385
+ evaluated, matching the "delete the test mail after test complete" requirement."""
386
+ for m in messages:
387
+ if m in SYSTEM_TEST_INBOX.messages:
388
+ SYSTEM_TEST_INBOX.messages.remove(m)
389
+
390
+
391
+ def _settle(org_id: str, connection_id: str, status: str, message_override: str | None = None) -> str:
392
+ path = _connection_path(org_id, connection_id)
393
+ db.update_doc(
394
+ path,
395
+ {
396
+ "status": status,
397
+ "status_message": message_override if message_override is not None else FAILURE_MESSAGES.get(status),
398
+ "verified_at": _now() if status == "verified" else None,
399
+ "dismissed": False, # a fresh result is news again, even if the last failure was dismissed
400
+ },
401
+ )
402
+ return status
backend/mailer_client.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The seam between the sending pipeline (backend/sending.py) and actual mail transport —
3
+ same pattern as backend/firestore_client.py for storage. Independent of LOCAL_MODE on
4
+ purpose: LOCAL_MODE governs storage (Firestore vs. the local shim), REAL_SEND_ENABLED
5
+ governs mail transport. You can want local storage with a real mailer (exactly the setup
6
+ used to verify a real send end-to-end without a GCP project) or, later, real storage with a
7
+ mock mailer (safe load-testing against prod-shaped data without actually emailing anyone).
8
+
9
+ Mailbox *verification* (backend/mailboxes.py's OTP round-trip) always uses the mock mailer
10
+ regardless of this flag — confirming a real round-trip would need reading the receiving
11
+ inbox back (IMAP), which is out of scope until the bounce-detection work in Phase 2 builds
12
+ that same scoped read capability. This module only governs the mailer used to actually send
13
+ a composed message once a connection is already marked verified.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import os
19
+
20
+ from backend.mock_mailer import MockInbox, MockMailer
21
+ from backend.smtp_mailer import SMTPMailer
22
+
23
+
24
+ def real_send_enabled() -> bool:
25
+ return os.getenv("REAL_SEND_ENABLED", "false").lower() == "true"
26
+
27
+
28
+ def get_mailer(kind: str, credentials: dict):
29
+ if not real_send_enabled():
30
+ return MockMailer(credentials, MockInbox())
31
+
32
+ if kind == "smtp":
33
+ return SMTPMailer(credentials)
34
+
35
+ raise NotImplementedError(
36
+ f"Real sending for mailbox kind {kind!r} isn't wired up yet — no real Google Cloud "
37
+ f"OAuth app exists (see docs/engineering/env-config-reference.md). Set "
38
+ f"REAL_SEND_ENABLED=false, or connect this org's mailbox via SMTP instead."
39
+ )
backend/messages.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The composer's canonical storage (docs/blueprint/adr/0003-html-source-of-truth-composer.md).
3
+ HTML is the one stored representation; live preview is just the frontend rendering this
4
+ field as-is — there's no backend computation involved in "preview," which is why there's no
5
+ separate preview endpoint/function here. Markdown and the block builder (deferred past
6
+ Phase 1 per the ADR) will compile down to this same field, one-way, when they're built.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import uuid
13
+ from datetime import datetime, timezone
14
+
15
+ from backend import firestore_client as db
16
+ from backend import orgs
17
+
18
+
19
+ def _now() -> str:
20
+ return datetime.now(timezone.utc).isoformat()
21
+
22
+
23
+ def _message_path(org_id: str, message_id: str) -> str:
24
+ return f"orgs/{org_id}/messages/{message_id}"
25
+
26
+
27
+ # Firestore documents stop at 1 MiB; the sent HTML always fits, an editable design with
28
+ # uploaded images inside it may not, and is then left out (the HTML alone still reopens).
29
+ _MAX_SOURCE_BYTES = 600_000
30
+
31
+
32
+ def create_message(org_id: str, actor_uid: str, subject: str, html_body: str,
33
+ mode: str | None = None, design: dict | None = None, automated: bool = False) -> str:
34
+ """`mode`/`design` are what the composer was holding when it sent, kept so the email can be
35
+ reopened or saved as a preset later exactly as it was built."""
36
+ if not automated:
37
+ orgs.require_permission(org_id, actor_uid, "send")
38
+ message_id = uuid.uuid4().hex
39
+ doc = {"subject": subject, "html_body": html_body, "created_at": _now()}
40
+ if mode in ("builder", "html"):
41
+ doc["mode"] = mode
42
+ if mode == "builder" and isinstance(design, dict) and len(json.dumps(design)) <= _MAX_SOURCE_BYTES:
43
+ doc["design"] = design
44
+ db.set_doc(_message_path(org_id, message_id), doc)
45
+ return message_id
46
+
47
+
48
+ def get_message(org_id: str, message_id: str) -> dict:
49
+ doc = db.get_doc(_message_path(org_id, message_id))
50
+ if doc is None:
51
+ raise orgs.NotFoundError(f"No message {message_id!r} in org {org_id!r}")
52
+ return doc
backend/mock_mailer.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Local stand-in for both halves of a real SMTP round-trip: a mailer that "sends" (an
3
+ outbound SMTP client) and an inbox that receives what was sent (standing in for M8ion's
4
+ own test mailbox during mailbox verification, per docs/product/srs.md FR-6/FR-7).
5
+
6
+ No real network call is ever made here — matches the prior build's LOCAL_MODE mailer
7
+ philosophy. A mailbox connection's credentials dict may carry a "_simulate" key (LOCAL_MODE
8
+ / test-only, never a real credential field) whose value drives one of the five verification
9
+ failure states from SRS FR-7, so the whole failure-handling branch can be exercised without
10
+ any real mail server:
11
+
12
+ "_simulate": "auth_fail" -> AuthError (SRS: "auth rejected")
13
+ "_simulate": "connection_fail" -> ConnectionFailure (SRS: "connection/network failure")
14
+ "_simulate": "silent_fail" -> send "succeeds" but nothing ever arrives
15
+ "_simulate": "partial_fail" -> only the first OTP of N arrives
16
+ "_simulate": "content_mismatch" -> all arrive, but with corrupted content
17
+ absent / "ok" -> everything arrives correctly
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from dataclasses import dataclass, field
23
+
24
+
25
+ class AuthError(Exception):
26
+ """Credentials were rejected outright — SRS FR-7 "auth rejected"."""
27
+
28
+
29
+ class ConnectionFailure(Exception):
30
+ """Couldn't reach the server at all — SRS FR-7 "connection/network failure"."""
31
+
32
+
33
+ @dataclass
34
+ class DeliveredMessage:
35
+ to_addr: str
36
+ subject: str
37
+ body: str
38
+ attachments: list = field(default_factory=list)
39
+ inline_images: list = field(default_factory=list)
40
+ headers: dict = field(default_factory=dict)
41
+
42
+
43
+ @dataclass
44
+ class MockInbox:
45
+ """Stands in for M8ion's own test mailbox. Messages land here only when MockMailer
46
+ actually "delivers" them — a silent-failure simulation means nothing shows up here
47
+ at all, exactly like a real dropped send would look from the receiving side."""
48
+
49
+ messages: list[DeliveredMessage] = field(default_factory=list)
50
+
51
+ def messages_to(self, to_addr: str) -> list[DeliveredMessage]:
52
+ return [m for m in self.messages if m.to_addr == to_addr]
53
+
54
+ def clear(self) -> None:
55
+ self.messages.clear()
56
+
57
+
58
+ class MockMailer:
59
+ """One instance represents one outbound connection attempt using a given set of
60
+ mailbox credentials. `inbox` is where successful sends land."""
61
+
62
+ def __init__(self, credentials: dict, inbox: MockInbox):
63
+ simulate = credentials.get("_simulate", "ok")
64
+ if simulate == "auth_fail":
65
+ raise AuthError("Authentication rejected for the supplied credentials")
66
+ if simulate == "connection_fail":
67
+ raise ConnectionFailure("Could not reach the mail server")
68
+ self._simulate = simulate
69
+ self.inbox = inbox
70
+ self._sent_count = 0
71
+
72
+ def configure(self, from_name: str = "", reply_to: str = "", save_sent_copy: bool = True) -> None:
73
+ self.from_name, self.reply_to, self.save_sent_copy = from_name, reply_to, save_sent_copy
74
+
75
+ def send(self, to_addr: str, subject: str, body: str, attachments=None, inline_images=None, headers=None) -> None:
76
+ self._sent_count += 1
77
+
78
+ if self._simulate == "silent_fail":
79
+ return # "accepted" by the caller's mental model, but never arrives anywhere
80
+
81
+ if self._simulate == "partial_fail" and self._sent_count > 1:
82
+ return # only the first message of a batch ever arrives
83
+
84
+ if self._simulate == "content_mismatch":
85
+ body = f"CORRUPTED::{body}"
86
+
87
+ self.inbox.messages.append(DeliveredMessage(
88
+ to_addr=to_addr, subject=subject, body=body,
89
+ attachments=list(attachments or []), inline_images=list(inline_images or []), headers=dict(headers or {}),
90
+ ))
backend/normalize.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Practical, honest normalization — not a textbook-complete 5NF engine (see the plan's
3
+ "feasibility note": BCNF/4NF/5NF require detecting multi-valued/join dependencies, which has
4
+ no safe general algorithm for arbitrary real-world data). What this module actually does:
5
+
6
+ - 1NF: handled at classification time (backend/databases.py splits delimiter-separated values
7
+ only in columns classified as "tag" — the one column type where a multi-value cell is
8
+ expected by design, not a guess).
9
+ - 2NF/3NF: real, mechanical functional-dependency discovery (a determinant column whose every
10
+ distinct value maps to exactly one value of another column, and which isn't itself a
11
+ candidate key) — automatically extracted into a natural-keyed lookup table.
12
+ - Beyond 3NF: only ever *suggested* (a plain-language reason attached), never auto-applied —
13
+ a composite pair of columns that together determine a third is flagged, not restructured.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from dataclasses import dataclass, field
19
+
20
+
21
+ @dataclass
22
+ class NormalizedTable:
23
+ name: str
24
+ columns: list[str]
25
+ rows: list[dict]
26
+
27
+
28
+ @dataclass
29
+ class NormalizationResult:
30
+ root: NormalizedTable
31
+ lookups: list[NormalizedTable] = field(default_factory=list)
32
+ suggestions: list[str] = field(default_factory=list)
33
+
34
+
35
+ def _distinct_count(rows: list[dict], col: str) -> int:
36
+ return len({row.get(col) for row in rows})
37
+
38
+
39
+ def discover_functional_dependencies(
40
+ rows: list[dict], headers: list[str], exclude_determinants: set[str] = frozenset(),
41
+ ) -> dict[str, set[str]]:
42
+ """{determinant: {columns it functionally determines}}. A column only qualifies as a
43
+ determinant if it has fewer distinct values than there are rows (otherwise it's a
44
+ candidate key, not a useful grouping column), more than one distinct value (otherwise
45
+ it's constant and splitting on it is meaningless), and isn't in `exclude_determinants` —
46
+ a per-row identity column (an email address) can look like a "determinant" purely because
47
+ duplicate rows collapse its distinct count, which isn't a real grouping dimension; it's
48
+ still fine for such a column to be a *dependent* of something else."""
49
+ n = len(rows)
50
+ deps: dict[str, set[str]] = {}
51
+ if n < 2:
52
+ return deps
53
+
54
+ for a in headers:
55
+ if a in exclude_determinants:
56
+ continue
57
+ distinct_a = _distinct_count(rows, a)
58
+ if distinct_a >= n or distinct_a <= 1:
59
+ continue
60
+ for b in headers:
61
+ if a == b:
62
+ continue
63
+ mapping: dict[object, object] = {}
64
+ consistent = True
65
+ for row in rows:
66
+ va, vb = row.get(a), row.get(b)
67
+ if va in mapping and mapping[va] != vb:
68
+ consistent = False
69
+ break
70
+ mapping[va] = vb
71
+ if consistent:
72
+ deps.setdefault(a, set()).add(b)
73
+ return deps
74
+
75
+
76
+ def normalize(
77
+ rows: list[dict], headers: list[str], root_name: str = "root", exclude_determinants: set[str] = frozenset(),
78
+ auto_split: bool = True,
79
+ ) -> NormalizationResult:
80
+ """Splits out one lookup table per determinant column (first-match-wins: once a column's
81
+ dependents are extracted, it isn't reconsidered as a dependent of a later determinant, to
82
+ avoid conflicting/overlapping splits), then scans what's left for a composite-determinant
83
+ signal worth flagging but not acting on. `exclude_determinants` — see
84
+ discover_functional_dependencies — keeps identity-like columns (email) from being treated
85
+ as a grouping dimension.
86
+
87
+ auto_split=False keeps every column in the one table and reports nothing. Uploads use that:
88
+ "A determines B" found in a few hundred rows is usually coincidence (names are nearly unique),
89
+ and moving real columns out of the sheet because of it hid people's data from them."""
90
+ if auto_split is False:
91
+ return NormalizationResult(
92
+ root=NormalizedTable(name=root_name, columns=list(headers), rows=[{c: r.get(c) for c in headers} for r in rows]),
93
+ )
94
+ deps = discover_functional_dependencies(rows, headers, exclude_determinants)
95
+
96
+ extracted_as_dependent: set[str] = set()
97
+ used_as_determinant: set[str] = set()
98
+ lookups: list[NormalizedTable] = []
99
+ for determinant, dependents in deps.items():
100
+ # A column already folded into another table as a dependent can't turn around and
101
+ # become a determinant itself — and a two-way dependency (A<->B, common whenever both
102
+ # sides happen to have the same distinct-value count, e.g. company <-> company_city)
103
+ # would otherwise get extracted TWICE, once from each direction, stripping both
104
+ # columns out of root instead of just one.
105
+ if determinant in extracted_as_dependent:
106
+ continue
107
+ dependents = {
108
+ d for d in dependents
109
+ if d not in extracted_as_dependent and d not in used_as_determinant and d != determinant
110
+ }
111
+ if not dependents:
112
+ continue
113
+ lookup_cols = [determinant, *sorted(dependents)]
114
+ seen_keys: set[object] = set()
115
+ lookup_rows = []
116
+ for row in rows:
117
+ key = row.get(determinant)
118
+ if key in seen_keys:
119
+ continue
120
+ seen_keys.add(key)
121
+ lookup_rows.append({c: row.get(c) for c in lookup_cols})
122
+ lookups.append(NormalizedTable(name=f"{determinant}_lookup", columns=lookup_cols, rows=lookup_rows))
123
+ used_as_determinant.add(determinant)
124
+ extracted_as_dependent.update(dependents)
125
+
126
+ root_columns = [h for h in headers if h not in extracted_as_dependent]
127
+ root_rows = [{c: row.get(c) for c in root_columns} for row in rows]
128
+
129
+ suggestions = _composite_dependency_suggestions(rows, root_columns, exclude_determinants)
130
+
131
+ return NormalizationResult(
132
+ root=NormalizedTable(name=root_name, columns=root_columns, rows=root_rows),
133
+ lookups=lookups,
134
+ suggestions=suggestions,
135
+ )
136
+
137
+
138
+ def _composite_dependency_suggestions(
139
+ rows: list[dict], headers: list[str], exclude_determinants: set[str] = frozenset(),
140
+ ) -> list[str]:
141
+ """A bounded (O(columns^2)) scan for pairs (a, b) that together determine a third column
142
+ c, where neither a nor b alone does — a BCNF/4NF-flavored signal. Reported as plain-
143
+ language text for a human to accept, never auto-applied."""
144
+ n = len(rows)
145
+ if n < 3:
146
+ return []
147
+ single_deps = discover_functional_dependencies(rows, headers, exclude_determinants)
148
+ suggestions: list[str] = []
149
+ candidate_headers = [h for h in headers if h not in exclude_determinants]
150
+
151
+ for i, a in enumerate(candidate_headers):
152
+ for b in candidate_headers[i + 1 :]:
153
+ pair_values = {(row.get(a), row.get(b)) for row in rows}
154
+ if len(pair_values) >= n:
155
+ continue # (a, b) together are already unique per row — not a useful grouping
156
+ for c in headers:
157
+ if c in (a, b):
158
+ continue
159
+ if c in single_deps.get(a, set()) or c in single_deps.get(b, set()):
160
+ continue # already explained by a single-column dependency
161
+ mapping: dict[tuple, object] = {}
162
+ consistent = True
163
+ for row in rows:
164
+ key = (row.get(a), row.get(b))
165
+ vc = row.get(c)
166
+ if key in mapping and mapping[key] != vc:
167
+ consistent = False
168
+ break
169
+ mapping[key] = vc
170
+ if consistent and len(mapping) < n:
171
+ suggestions.append(
172
+ f"Columns '{a}' and '{b}' together always determine '{c}' — "
173
+ f"consider extracting a lookup table (not applied automatically)."
174
+ )
175
+ return suggestions
backend/orgs.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The org/owner/role model — the foundation everything else (mailbox connections, contacts,
3
+ messages, sends) is scoped by. See docs/blueprint/blueprint.md "Core entities" and
4
+ docs/product/srs.md FR-1 through FR-3.
5
+
6
+ Firestore layout (see backend/firestore_client.py for the local/real seam):
7
+ orgs/{org_id} — {name, owner_uid, created_at}
8
+ orgs/{org_id}/members/{uid} — {role, added_at, email?}
9
+ orgs/{org_id}/roles/{key} — {name, permissions} (an edited built-in role, or a
10
+ custom one; built-ins not stored use their defaults)
11
+ user_orgs/{uid} — {org_ids: {org_id: role, ...}} (reverse index,
12
+ kept in sync on every membership write, so
13
+ "which orgs does this user belong to" doesn't
14
+ require scanning every org)
15
+
16
+ One person (one Firebase uid) can own or belong to multiple orgs — the reverse index is
17
+ what makes that lookup cheap.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import uuid
23
+ from datetime import datetime, timezone
24
+
25
+ from backend import firestore_client as db
26
+ from backend.core.constants import BUILTIN_ROLES, ORG_CREATOR_ROLE, PERMISSIONS, ROLE_ALIASES, ROLE_RANK, ROLE_SPACES, SPACES
27
+
28
+
29
+ class PermissionError_(Exception):
30
+ """Raised when an actor's role doesn't meet the required rank for an action."""
31
+
32
+
33
+ class NotFoundError(Exception):
34
+ """Raised when an org or membership doesn't exist."""
35
+
36
+
37
+ def _now() -> str:
38
+ return datetime.now(timezone.utc).isoformat()
39
+
40
+
41
+ def _member_path(org_id: str, uid: str) -> str:
42
+ return f"orgs/{org_id}/members/{uid}"
43
+
44
+
45
+ def _members_prefix(org_id: str) -> str:
46
+ return f"orgs/{org_id}/members/"
47
+
48
+
49
+ def _user_orgs_path(uid: str) -> str:
50
+ return f"user_orgs/{uid}"
51
+
52
+
53
+ def _set_reverse_index(uid: str, org_id: str, role: str) -> None:
54
+ doc = db.get_doc(_user_orgs_path(uid)) or {"org_ids": {}}
55
+ doc["org_ids"][org_id] = role
56
+ db.set_doc(_user_orgs_path(uid), doc)
57
+
58
+
59
+ def _clear_reverse_index(uid: str, org_id: str) -> None:
60
+ doc = db.get_doc(_user_orgs_path(uid))
61
+ if doc and org_id in doc.get("org_ids", {}):
62
+ del doc["org_ids"][org_id]
63
+ db.set_doc(_user_orgs_path(uid), doc)
64
+
65
+
66
+ def create_org(owner_uid: str, name: str, kind: str | None = None) -> str:
67
+ """Creates a new org with `owner_uid` as its owner. Returns the new org_id. A single
68
+ uid can own — and separately create — more than one org (SRS note under FR-2).
69
+ `kind` is "personal" for an individual's own org (see backend/accounts.py)."""
70
+ org_id = uuid.uuid4().hex
71
+ doc = {"name": name, "owner_uid": owner_uid, "created_at": _now()}
72
+ if kind:
73
+ doc["kind"] = kind
74
+ db.set_doc(f"orgs/{org_id}", doc)
75
+ db.set_doc(_member_path(org_id, owner_uid), {"role": ORG_CREATOR_ROLE, "added_at": _now()})
76
+ _set_reverse_index(owner_uid, org_id, ORG_CREATOR_ROLE)
77
+ return org_id
78
+
79
+
80
+ def get_org(org_id: str) -> dict:
81
+ org = db.get_doc(f"orgs/{org_id}")
82
+ if org is None:
83
+ raise NotFoundError(f"No org {org_id!r}")
84
+ return org
85
+
86
+
87
+ def get_role(org_id: str, uid: str) -> str | None:
88
+ """The uid's role in this org, or None if they aren't a member."""
89
+ membership = db.get_doc(_member_path(org_id, uid))
90
+ return membership["role"] if membership else None
91
+
92
+
93
+ def require_role(org_id: str, uid: str, minimum_role: str) -> str:
94
+ """Raises PermissionError_ unless uid's role in org_id ranks at or above
95
+ minimum_role. Returns the actor's actual role on success. Kept for rank checks between
96
+ built-in roles; feature checks use require_permission. Custom roles rank lowest."""
97
+ role = get_role(org_id, uid)
98
+ if role is None:
99
+ raise PermissionError_(f"{uid!r} is not a member of org {org_id!r}")
100
+ if ROLE_RANK.get(role, 0) < ROLE_RANK[minimum_role]:
101
+ raise PermissionError_(
102
+ f"{uid!r} has role {role!r} in org {org_id!r}, needs at least {minimum_role!r}"
103
+ )
104
+ return role
105
+
106
+
107
+ def _role_path(org_id: str, key: str) -> str:
108
+ return f"orgs/{org_id}/roles/{key}"
109
+
110
+
111
+ def list_roles(org_id: str) -> list[dict]:
112
+ """Every role in the org: the built-ins (with any edits) first, then custom ones."""
113
+ prefix = f"orgs/{org_id}/roles/"
114
+ stored = {path[len(prefix):]: data for path, data in db.query_prefix(prefix).items()}
115
+ roles = []
116
+ for key, default in BUILTIN_ROLES.items():
117
+ data = default if key == ORG_CREATOR_ROLE else stored.get(key, default)
118
+ roles.append({"key": key, "name": default["name"], "permissions": list(data["permissions"]), "builtin": True})
119
+ for key, data in sorted(stored.items(), key=lambda kv: kv[1].get("name", "").lower()):
120
+ if key not in BUILTIN_ROLES:
121
+ roles.append({"key": key, "name": data["name"], "permissions": list(data["permissions"]), "builtin": False})
122
+ return roles
123
+
124
+
125
+ def permissions_for(org_id: str, role: str) -> set[str]:
126
+ role = ROLE_ALIASES.get(role, role)
127
+ if role == ORG_CREATOR_ROLE:
128
+ return set(PERMISSIONS)
129
+ stored = db.get_doc(_role_path(org_id, role))
130
+ if stored is not None:
131
+ return set(stored["permissions"])
132
+ return set(BUILTIN_ROLES.get(role, {"permissions": []})["permissions"])
133
+
134
+
135
+ def require_permission(org_id: str, uid: str, permission: str | None = None) -> str:
136
+ """Raises PermissionError_ unless uid is a member of org_id whose role allows
137
+ `permission` (None: being a member is enough). Returns the actor's role."""
138
+ role = get_role(org_id, uid)
139
+ if role is None:
140
+ raise PermissionError_(f"{uid!r} is not a member of org {org_id!r}")
141
+ if permission is not None and permission not in effective_permissions(org_id, uid):
142
+ raise PermissionError_(f"Your role doesn't allow this ({PERMISSIONS[permission].lower()})")
143
+ return role
144
+
145
+
146
+ def extra_roles_of(org_id: str, uid: str) -> list[str]:
147
+ doc = db.get_doc(_member_path(org_id, uid)) or {}
148
+ return list(doc.get("extra_roles", []))
149
+
150
+
151
+ def all_roles_of(org_id: str, uid: str) -> list[str]:
152
+ """The main role first, then any extra roles. Someone can hold several."""
153
+ role = get_role(org_id, uid)
154
+ return [role, *extra_roles_of(org_id, uid)] if role else []
155
+
156
+
157
+ def effective_permissions(org_id: str, uid: str) -> set[str]:
158
+ out: set[str] = set()
159
+ for role in all_roles_of(org_id, uid):
160
+ out |= permissions_for(org_id, role)
161
+ return out
162
+
163
+
164
+ def spaces_for(org_id: str, uid: str) -> list[dict]:
165
+ """Every area, each marked allowed or not for this member."""
166
+ opened: set[str] = set()
167
+ for role in all_roles_of(org_id, uid):
168
+ opened |= set(ROLE_SPACES.get(ROLE_ALIASES.get(role, role), []))
169
+ return [{"key": k, "label": v[0], "about": v[1], "allowed": k in opened} for k, v in SPACES.items()]
170
+
171
+
172
+ def set_extra_roles(org_id: str, actor_uid: str, target_uid: str, roles: list[str]) -> None:
173
+ """Gives a member further roles beside their main one. Same rules as changing a role."""
174
+ _check_manage(org_id, actor_uid, target_uid)
175
+ roles = [r for r in dict.fromkeys(roles)]
176
+ for role in roles:
177
+ _check_grant(org_id, actor_uid, role)
178
+ doc = db.get_doc(_member_path(org_id, target_uid))
179
+ doc["extra_roles"] = [r for r in roles if r != doc["role"]]
180
+ db.set_doc(_member_path(org_id, target_uid), doc)
181
+
182
+
183
+ def _role_exists(org_id: str, role: str) -> bool:
184
+ return role in BUILTIN_ROLES or role in ROLE_ALIASES or db.get_doc(_role_path(org_id, role)) is not None
185
+
186
+
187
+ def _check_grant(org_id: str, actor_uid: str, role: str) -> str:
188
+ """The checks shared by inviting, adding and changing someone's role. Nobody can hand
189
+ out ownership, only an owner can hand out admin, and nobody can hand out more than
190
+ they can do themselves."""
191
+ if role == ORG_CREATOR_ROLE:
192
+ raise PermissionError_("Ownership can't be granted — only by creating the org")
193
+ if not _role_exists(org_id, role):
194
+ raise ValueError(f"Unknown role {role!r}")
195
+ actor_role = require_permission(org_id, actor_uid, "manage_team")
196
+ if ROLE_ALIASES.get(role, role) == "admin" and actor_role != ORG_CREATOR_ROLE:
197
+ raise PermissionError_("Only an owner can make someone an admin")
198
+ if not permissions_for(org_id, role) <= permissions_for(org_id, actor_role):
199
+ raise PermissionError_("You can't give someone more access than you have")
200
+ return actor_role
201
+
202
+
203
+ def _check_manage(org_id: str, actor_uid: str, target_uid: str) -> str:
204
+ """Checks before changing or removing an existing member. Returns their role."""
205
+ target_role = get_role(org_id, target_uid)
206
+ if target_role is None:
207
+ raise NotFoundError(f"{target_uid!r} is not a member of org {org_id!r}")
208
+ if target_role == ORG_CREATOR_ROLE:
209
+ raise PermissionError_("The owner can't be changed or removed")
210
+ actor_role = require_permission(org_id, actor_uid, "manage_team")
211
+ if target_role == "admin" and actor_role != ORG_CREATOR_ROLE:
212
+ raise PermissionError_("Only an owner can change or remove an admin")
213
+ return target_role
214
+
215
+
216
+ def add_member(org_id: str, actor_uid: str, target_uid: str, role: str, email: str = "") -> None:
217
+ """actor_uid adds target_uid to org_id with the given role (see _check_grant)."""
218
+ _check_grant(org_id, actor_uid, role)
219
+ doc = {"role": role, "added_at": _now()}
220
+ if email:
221
+ doc["email"] = email
222
+ db.set_doc(_member_path(org_id, target_uid), doc)
223
+ _set_reverse_index(target_uid, org_id, role)
224
+
225
+
226
+ def join(org_id: str, uid: str, role: str, email: str = "") -> None:
227
+ """Adds uid with an already-approved role (an accepted invite). Never lowers or
228
+ replaces the role of someone who is already a member."""
229
+ if get_role(org_id, uid) is not None:
230
+ return
231
+ doc = {"role": role, "added_at": _now()}
232
+ if email:
233
+ doc["email"] = email
234
+ db.set_doc(_member_path(org_id, uid), doc)
235
+ _set_reverse_index(uid, org_id, role)
236
+
237
+
238
+ def change_member_role(org_id: str, actor_uid: str, target_uid: str, role: str) -> None:
239
+ _check_manage(org_id, actor_uid, target_uid)
240
+ _check_grant(org_id, actor_uid, role)
241
+ doc = db.get_doc(_member_path(org_id, target_uid))
242
+ doc["role"] = role
243
+ db.set_doc(_member_path(org_id, target_uid), doc)
244
+ _set_reverse_index(target_uid, org_id, role)
245
+
246
+
247
+ def remove_member(org_id: str, actor_uid: str, target_uid: str) -> None:
248
+ """Someone who can manage the team can remove anyone except the owner; only an
249
+ owner can remove an admin."""
250
+ _check_manage(org_id, actor_uid, target_uid)
251
+ db.delete_doc(_member_path(org_id, target_uid))
252
+ _clear_reverse_index(target_uid, org_id)
253
+
254
+
255
+ def leave(org_id: str, uid: str) -> None:
256
+ """A member leaves on their own. The owner can't leave their own org."""
257
+ role = require_permission(org_id, uid)
258
+ if role == ORG_CREATOR_ROLE:
259
+ raise PermissionError_("The owner can't leave their own organisation")
260
+ db.delete_doc(_member_path(org_id, uid))
261
+ _clear_reverse_index(uid, org_id)
262
+
263
+
264
+ def save_role(org_id: str, actor_uid: str, key: str | None, name: str, permissions: list[str]) -> str:
265
+ """Creates a custom role (key None) or edits one, built-ins included except Owner.
266
+ Returns the role's key."""
267
+ actor_role = require_permission(org_id, actor_uid, "manage_team")
268
+ unknown = [p for p in permissions if p not in PERMISSIONS]
269
+ if unknown:
270
+ raise ValueError(f"Unknown permission {unknown[0]!r}")
271
+ if not set(permissions) <= permissions_for(org_id, actor_role):
272
+ raise PermissionError_("You can't give a role more access than you have")
273
+ if key == ORG_CREATOR_ROLE:
274
+ raise PermissionError_("The Owner role can't be changed")
275
+ if key is None:
276
+ name = (name or "").strip()
277
+ if not name or len(name) > 40:
278
+ raise ValueError("Give the role a name of up to 40 characters")
279
+ if any(r["name"].lower() == name.lower() for r in list_roles(org_id)):
280
+ raise ValueError(f"There is already a role called {name!r}")
281
+ key = "custom-" + uuid.uuid4().hex[:10]
282
+ elif not _role_exists(org_id, key):
283
+ raise NotFoundError(f"No role {key!r}")
284
+ if key in BUILTIN_ROLES:
285
+ name = BUILTIN_ROLES[key]["name"]
286
+ if key == "admin" and actor_role != ORG_CREATOR_ROLE:
287
+ raise PermissionError_("Only an owner can change the Admin role")
288
+ else:
289
+ stored = db.get_doc(_role_path(org_id, key))
290
+ name = (name or "").strip() or (stored or {}).get("name", "")
291
+ db.set_doc(_role_path(org_id, key), {"name": name, "permissions": sorted(set(permissions))})
292
+ return key
293
+
294
+
295
+ def delete_role(org_id: str, actor_uid: str, key: str) -> None:
296
+ """Removes a custom role nobody holds, or resets an edited built-in to its default."""
297
+ require_permission(org_id, actor_uid, "manage_team")
298
+ if key == ORG_CREATOR_ROLE:
299
+ raise PermissionError_("The Owner role can't be changed")
300
+ if key not in BUILTIN_ROLES:
301
+ if any(m["role"] == key for m in list_members(org_id).values()):
302
+ raise ValueError("Move everyone off this role before deleting it")
303
+ db.delete_doc(_role_path(org_id, key))
304
+
305
+
306
+ def list_members(org_id: str) -> dict[str, dict]:
307
+ """{uid: {role, added_at}} for every member of org_id."""
308
+ prefix = _members_prefix(org_id)
309
+ docs = db.query_prefix(prefix)
310
+ return {path[len(prefix):]: data for path, data in docs.items()}
311
+
312
+
313
+ def list_orgs_for_user(uid: str) -> dict[str, str]:
314
+ """{org_id: role} for every org this uid belongs to, across all their orgs."""
315
+ doc = db.get_doc(_user_orgs_path(uid))
316
+ return dict(doc["org_ids"]) if doc else {}
backend/overview.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The dashboard's numbers in one call: lists and people, mailboxes and their health, recent
3
+ sends and how they went, forms and presets. Read-only, and every count comes from the same
4
+ stores the other pages read, so the dashboard never disagrees with them.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from datetime import datetime, timedelta, timezone
10
+
11
+ from backend import collect, databases, mailboxes, orgs, presets, sending
12
+
13
+ _RECENT_DAYS = 30
14
+
15
+
16
+ def _parse(ts: str | None) -> datetime | None:
17
+ if not ts:
18
+ return None
19
+ try:
20
+ return datetime.fromisoformat(ts)
21
+ except ValueError:
22
+ return None
23
+
24
+
25
+ def get_overview(org_id: str, actor_uid: str) -> dict:
26
+ orgs.require_permission(org_id, actor_uid)
27
+
28
+ lists = [{"database_id": did, **d} for did, d in databases.list_databases(org_id).items()]
29
+ boxes = list(mailboxes.list_mailboxes(org_id).values())
30
+ sends = sending.list_sends(org_id, actor_uid, limit=500)
31
+ forms = [k for k in collect.list_keys(org_id, actor_uid) if not k.get("revoked")]
32
+ saved_presets = presets.list_presets(org_id, actor_uid)
33
+
34
+ cutoff = datetime.now(timezone.utc) - timedelta(days=_RECENT_DAYS)
35
+ recent = [s for s in sends if (_parse(s["sent_at"]) or cutoff) > cutoff]
36
+ delivered = sum(s["sent"] for s in recent)
37
+ failed = sum(s["failed"] for s in recent)
38
+
39
+ # One point per day for the last 30 days, oldest first, for the activity chart.
40
+ by_day: dict[str, int] = {}
41
+ for s in recent:
42
+ day = (_parse(s["sent_at"]) or cutoff).date().isoformat()
43
+ by_day[day] = by_day.get(day, 0) + s["sent"]
44
+ today = datetime.now(timezone.utc).date()
45
+ activity = [
46
+ {"day": (today - timedelta(days=i)).isoformat(), "sent": by_day.get((today - timedelta(days=i)).isoformat(), 0)}
47
+ for i in range(_RECENT_DAYS - 1, -1, -1)
48
+ ]
49
+
50
+ names = {d["database_id"]: d["name"] for d in lists}
51
+ return {
52
+ "people": sum(d.get("row_count", 0) for d in lists if not d.get("disabled")),
53
+ "lists": len(lists),
54
+ "mailboxes": {
55
+ "total": len(boxes),
56
+ "verified": sum(1 for b in boxes if b.get("status") == "verified"),
57
+ "needs_attention": sum(1 for b in boxes if b.get("status") not in ("verified", "pending_verification") and not b.get("dismissed")),
58
+ },
59
+ "sends_30d": {"campaigns": len(recent), "delivered": delivered, "failed": failed},
60
+ "forms": len(forms),
61
+ "presets": len(saved_presets),
62
+ "activity": activity,
63
+ "recent_sends": [s | {"list_name": names.get(s["database_id"], "Deleted list")} for s in sends[:8]],
64
+ "largest_lists": sorted(
65
+ ({"database_id": d["database_id"], "name": d["name"], "row_count": d.get("row_count", 0)} for d in lists),
66
+ key=lambda d: d["row_count"], reverse=True,
67
+ )[:5],
68
+ }
backend/presets.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Saved email presets: a whole message (subject plus either a drag-and-drop design or raw HTML)
3
+ that a sender can start the next campaign from. Built-in starter layouts live in the frontend;
4
+ only the ones a sender saves are stored, per org at orgs/{org_id}/presets/{id}.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import uuid
11
+ from datetime import datetime, timezone
12
+
13
+ from backend import firestore_client as db
14
+ from backend import orgs
15
+
16
+ _MAX_NAME = 80
17
+ _MAX_SUBJECT = 300
18
+ # A stored document must stay under Firestore's 1 MB limit, images included.
19
+ _MAX_CONTENT_BYTES = 900_000
20
+ _MODES = ("builder", "html")
21
+
22
+
23
+ def _now() -> str:
24
+ return datetime.now(timezone.utc).isoformat()
25
+
26
+
27
+ def _prefix(org_id: str) -> str:
28
+ return f"orgs/{org_id}/presets/"
29
+
30
+
31
+ def _path(org_id: str, preset_id: str) -> str:
32
+ return f"{_prefix(org_id)}{preset_id}"
33
+
34
+
35
+ def _clean(name: str, subject: str, mode: str, design: dict | None, html: str) -> dict:
36
+ name = name.strip()
37
+ if not name or len(name) > _MAX_NAME:
38
+ raise ValueError(f"Give the preset a name of at most {_MAX_NAME} characters")
39
+ if len(subject) > _MAX_SUBJECT:
40
+ raise ValueError("The subject is too long")
41
+ if mode not in _MODES:
42
+ raise ValueError("A preset is either a drag-and-drop design or HTML")
43
+ if mode == "builder" and not isinstance(design, dict):
44
+ raise ValueError("This preset has no design to save")
45
+ size = len(json.dumps(design or {})) + len(html.encode())
46
+ if size > _MAX_CONTENT_BYTES:
47
+ raise ValueError("This preset is too large to save. Use smaller images and try again")
48
+ return {"name": name, "subject": subject, "mode": mode, "design": design if mode == "builder" else None, "html": html}
49
+
50
+
51
+ def create_preset(org_id: str, actor_uid: str, name: str, subject: str, mode: str, design: dict | None, html: str) -> str:
52
+ orgs.require_permission(org_id, actor_uid, "edit_emails")
53
+ data = _clean(name, subject, mode, design, html)
54
+ preset_id = uuid.uuid4().hex
55
+ db.set_doc(_path(org_id, preset_id), data | {"created_at": _now(), "updated_at": _now()})
56
+ return preset_id
57
+
58
+
59
+ def update_preset(org_id: str, actor_uid: str, preset_id: str, name: str, subject: str, mode: str,
60
+ design: dict | None, html: str) -> None:
61
+ orgs.require_permission(org_id, actor_uid, "edit_emails")
62
+ get_preset(org_id, preset_id)
63
+ db.update_doc(_path(org_id, preset_id), _clean(name, subject, mode, design, html) | {"updated_at": _now()})
64
+
65
+
66
+ def delete_preset(org_id: str, actor_uid: str, preset_id: str) -> None:
67
+ orgs.require_permission(org_id, actor_uid, "edit_emails")
68
+ get_preset(org_id, preset_id)
69
+ db.delete_doc(_path(org_id, preset_id))
70
+
71
+
72
+ def get_preset(org_id: str, preset_id: str) -> dict:
73
+ doc = db.get_doc(_path(org_id, preset_id))
74
+ if doc is None:
75
+ raise orgs.NotFoundError(f"No preset {preset_id!r} in org {org_id!r}")
76
+ return doc
77
+
78
+
79
+ def list_presets(org_id: str, actor_uid: str) -> list[dict]:
80
+ orgs.require_permission(org_id, actor_uid)
81
+ prefix = _prefix(org_id)
82
+ items = [data | {"preset_id": path[len(prefix):]} for path, data in db.query_prefix(prefix).items()]
83
+ return sorted(items, key=lambda p: p.get("updated_at", ""), reverse=True)
backend/rate_limiter.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Basic per-org hourly send cap (docs/blueprint/adr/0004, blueprint "Rate limiting"). Phase 1
3
+ scope only: a rolling window enforced server-side. Anomaly detection and the 4-stage
4
+ escalation (detect -> block -> silently_report -> auto_temporary_ban) are Phase 2
5
+ (docs/product/checklist.md) — this module only ever does stage one, "detect (and block)".
6
+
7
+ Rolling, not fixed-hour-boundary, per ADR-0004 — avoids the burst-at-the-top-of-the-hour
8
+ gap a naive reset would allow. Recorded timestamps live in the local store now; the
9
+ blueprint's eventual home for this is Redis/Memorystore, not Firestore (same reasoning as
10
+ the old due-job queue: don't put a perpetually-touched counter in a serverless-priced store).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import time
16
+
17
+ from backend import local_store
18
+ from backend.core.constants import DEFAULT_HOURLY_SEND_CAP
19
+
20
+ _WINDOW_SECONDS = 3600
21
+
22
+
23
+ class RateLimitExceeded(Exception):
24
+ def __init__(self, org_id: str, requested: int, remaining: int):
25
+ self.org_id = org_id
26
+ self.requested = requested
27
+ self.remaining = remaining
28
+ super().__init__(
29
+ f"org {org_id!r} requested {requested} sends but only {remaining} remain "
30
+ f"in the current rolling hour"
31
+ )
32
+
33
+
34
+ def _counter_path(org_id: str) -> str:
35
+ return f"rate_counters/{org_id}"
36
+
37
+
38
+ def _current_timestamps(org_id: str, now: float) -> list[float]:
39
+ doc = local_store.get_doc(_counter_path(org_id))
40
+ timestamps = doc["timestamps"] if doc else []
41
+ return [t for t in timestamps if now - t < _WINDOW_SECONDS]
42
+
43
+
44
+ def remaining_capacity(org_id: str, hourly_cap: int = DEFAULT_HOURLY_SEND_CAP) -> int:
45
+ now = time.time()
46
+ used = len(_current_timestamps(org_id, now))
47
+ return max(0, hourly_cap - used)
48
+
49
+
50
+ def check_and_consume(org_id: str, count: int, hourly_cap: int = DEFAULT_HOURLY_SEND_CAP) -> None:
51
+ """Reserves `count` sends against org_id's rolling-hour cap, all at once — a batch
52
+ either entirely fits or the whole call is rejected (Phase 1 simplification: no partial
53
+ sends within a single batch). Raises RateLimitExceeded if it doesn't fit. Server-side
54
+ only — nothing here is ever populated from a client-supplied value."""
55
+ now = time.time()
56
+ timestamps = _current_timestamps(org_id, now)
57
+ remaining = max(0, hourly_cap - len(timestamps))
58
+ if count > remaining:
59
+ raise RateLimitExceeded(org_id, count, remaining)
60
+
61
+ timestamps.extend([now] * count)
62
+ local_store.set_doc(_counter_path(org_id), {"timestamps": timestamps})
63
+
64
+
65
+ def allow_hit(bucket: str, limit: int, window_seconds: int) -> bool:
66
+ """Generic rolling-window counter for anything that is not an org send (e.g. the public
67
+ collection endpoint's per-key / per-IP / per-address limits). Records the hit and returns
68
+ True if it is within `limit` hits per `window_seconds`; returns False (and records
69
+ nothing) if it would exceed the limit. Always the local store, never Firestore."""
70
+ now = time.time()
71
+ path = f"rate_buckets/{bucket}"
72
+ doc = local_store.get_doc(path)
73
+ hits = [t for t in (doc["timestamps"] if doc else []) if now - t < window_seconds]
74
+ if len(hits) >= limit:
75
+ return False
76
+ hits.append(now)
77
+ local_store.set_doc(path, {"timestamps": hits})
78
+ return True
backend/rename_suggest.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Suggests short, readable column names for headers that came from form questions or exports
2
+ ("Phone Number (WhatsApp preferred)" -> "Phone"). Pure regex and string rules: no state, nothing
3
+ is renamed here. The caller shows the suggestion and the user accepts it."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import re
8
+
9
+ # (pattern on the lowercased header, suggested name, reason). First match wins, so order matters.
10
+ _KNOWN: list[tuple[re.Pattern[str], str, str]] = [
11
+ (re.compile(r"^(timestamp|submitted( at| on)?|submission (date|time)|date submitted)$"), "Submitted", "form timestamp"),
12
+ (re.compile(r"e-?mail"), "Email", "holds email addresses"),
13
+ (re.compile(r"date of birth|birth ?day|\bd\.?o\.?b\b"), "Date of birth", "date of birth"),
14
+ (re.compile(r"\bage\s*(range|group|bracket)\b|\bage\b"), "Age range", "age"),
15
+ (re.compile(r"\b(gender|sex)\b"), "Gender", "gender"),
16
+ (re.compile(r"hours?\s+(per|a|each)\s+week|weekly hours"), "Weekly hours", "hours per week"),
17
+ (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"),
18
+ (re.compile(r"join (the|our) .*(group|link|community|channel)|group link|invite link"), "Group link", "group invite"),
19
+ (re.compile(r"school|institution|universit|college|organi[sz]ation|company|employer|workplace"), "Organization", "where they study or work"),
20
+ (re.compile(r"\b(town|city)\b|residence|where do you live|\blocation\b"), "City", "where they live"),
21
+ (re.compile(r"current (status|occupation)|occupation|employment status"), "Status", "current status"),
22
+ (re.compile(r"phone|mobile|whats\s?app|\btel(ephone)?\b|contact (number|no)|cell"), "Phone", "phone number"),
23
+ (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"),
24
+ ]
25
+
26
+ _PAREN = re.compile(r"\s*[\(\[][^)\]]*[\)\]]")
27
+ _LEAD = re.compile(r"^(please|kindly|enter|provide|state|type|what(?:'s| is| are)?|which|your|the)\s+", re.I)
28
+ _CLAUSE_SPLIT = re.compile(r"\s*(?:/|\||:| - |,|;| that | which | you | to )\s*")
29
+ _MAX_PLAIN = 28
30
+
31
+
32
+ def _clean(header: str) -> str:
33
+ text = _PAREN.sub("", header).strip().rstrip("?.:! ")
34
+ for _ in range(3):
35
+ stripped = _LEAD.sub("", text)
36
+ if stripped == text:
37
+ break
38
+ text = stripped
39
+ text = _CLAUSE_SPLIT.split(text)[0].strip() or text
40
+ return text[:1].upper() + text[1:] if text else text
41
+
42
+
43
+ def _is_messy(header: str) -> bool:
44
+ return bool(_PAREN.search(header)) or "?" in header or len(header) > _MAX_PLAIN or "/" in header
45
+
46
+
47
+ def suggest_rename(header: str, column_type: str = "text", taken: set[str] | None = None) -> dict | None:
48
+ """Returns {"suggested", "reason"} or None. `taken` is the lowercase set of other column
49
+ names, so a suggestion never collides with one that exists."""
50
+ taken = taken or set()
51
+ original = header.strip()
52
+ if not original:
53
+ return None
54
+ low = original.lower()
55
+
56
+ suggestion: str | None = None
57
+ reason = ""
58
+ for pattern, name, why in _KNOWN:
59
+ if pattern.search(low):
60
+ suggestion, reason = name, why
61
+ break
62
+
63
+ # A bare "Name" or "Phone" header is already fine; known rules only fire when the header
64
+ # is long, wrapped in brackets, a question, or not already the short name.
65
+ if suggestion and original.lower() == suggestion.lower():
66
+ return None
67
+ if suggestion and not _is_messy(original) and len(original) <= len(suggestion) + 4:
68
+ return None
69
+
70
+ if suggestion is None:
71
+ if not _is_messy(original):
72
+ return None
73
+ cleaned = _clean(original)
74
+ if cleaned and len(cleaned) <= _MAX_PLAIN and cleaned.lower() != low:
75
+ suggestion, reason = cleaned, "shorter wording"
76
+ elif column_type == "email":
77
+ suggestion, reason = "Email", "holds email addresses"
78
+ elif column_type == "contact":
79
+ suggestion, reason = "Phone", "holds phone numbers"
80
+ else:
81
+ return None
82
+
83
+ if suggestion.lower() == low or suggestion.lower() in taken:
84
+ return None
85
+ return {"suggested": suggestion, "reason": reason}
86
+
87
+
88
+ def suggest_renames(columns: list[dict]) -> list[dict]:
89
+ """One suggestion per column that has one, each avoiding names already used by other columns
90
+ and by earlier suggestions."""
91
+ names = {c["name"].lower() for c in columns}
92
+ claimed: set[str] = set()
93
+ out: list[dict] = []
94
+ for col in columns:
95
+ taken = (names - {col["name"].lower()}) | claimed
96
+ hit = suggest_rename(col["name"], col.get("type", "text"), taken)
97
+ if hit:
98
+ claimed.add(hit["suggested"].lower())
99
+ out.append({"column": col["name"], **hit})
100
+ return out
backend/sending.py ADDED
@@ -0,0 +1,656 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Manual send — the Phase 1 slice of docs/blueprint/blueprint.md "Sending pipeline". Every
3
+ send is tracked per-recipient (SRS FR-18), never only per-broadcast — this is also what
4
+ billing (per-recipient, ADR-0005) and rate limiting (per-send, not per-batch) both read
5
+ from.
6
+
7
+ Scheduled sends and bounce/DSN detection (SRS FR-19/20) are Phase 2 — this module only
8
+ covers a synchronous, immediate, manual send (a "Campaign" in the frontend's terms — see
9
+ frontend/src/pages/Campaigns.tsx — not yet an automation), which is enough to prove
10
+ per-recipient status tracking end-to-end. Which mailer actually does the sending (mock vs.
11
+ real SMTP) is decided by backend/mailer_client.py's REAL_SEND_ENABLED flag, not by anything
12
+ in this file.
13
+
14
+ Recipients come from backend/databases.py (a database's rows), not a flat contact list — each
15
+ row's own column values are substituted into {Placeholder} tokens in the subject/body before
16
+ that recipient's copy is sent, via substitute_placeholders.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import base64
22
+ import logging
23
+ import threading
24
+ import time
25
+ import uuid
26
+ from datetime import datetime, timezone
27
+
28
+ from backend import brands, certificates, databases, delivery, email_parts, firestore_client as db, mailboxes, mailer_client, messages, orgs, rate_limiter, settings, templating, unsubscribe
29
+ from backend.mock_mailer import AuthError, ConnectionFailure
30
+
31
+ log = logging.getLogger(__name__)
32
+
33
+ def _now() -> str:
34
+ return datetime.now(timezone.utc).isoformat()
35
+
36
+
37
+ def _send_path(org_id: str, send_id: str) -> str:
38
+ return f"orgs/{org_id}/sends/{send_id}"
39
+
40
+
41
+ def substitute_placeholders(template: str, row: dict, columns: list[dict] | None = None, html: bool = False) -> str:
42
+ """Renders one recipient's copy of `template` (see backend/templating.py): {ColumnName} is
43
+ replaced by that row's value (blank if the row has none — a gap for one row, not an error),
44
+ {Name|fallback} covers blanks, list columns become bullets or "A, B and C", and
45
+ {if ...}{else}{/if} blocks pick content by the row's values. With html=True, row values are
46
+ escaped so they cannot become markup."""
47
+ return templating.render(template, row, columns, html=html)
48
+
49
+
50
+ def _template_problems(subject: str, html_body: str, columns: list[dict]) -> list[str]:
51
+ # Checked separately: a block opened in the subject must not be "closed" by the body.
52
+ return list(dict.fromkeys(
53
+ templating.validate_template(subject, columns) + templating.validate_template(html_body, columns)
54
+ ))
55
+
56
+
57
+ def preview_render(
58
+ org_id: str, database_id: str, subject: str, html_body: str,
59
+ segment: list[dict] | None = None, index: int = 0, email_column: str | None = None,
60
+ ) -> dict:
61
+ """What recipient number `index` (of those the segment matches) would receive, using the
62
+ same renderer as the real send, plus any template problems that would block a send."""
63
+ database = databases.get_database(org_id, database_id)
64
+ columns = database["columns"]
65
+ problems = _template_problems(subject, html_body, columns)
66
+ rows = databases.list_rows(org_id, database_id)
67
+ if segment:
68
+ rows = databases.apply_segment(rows, columns, segment)
69
+ email_column = _email_column(database, email_column)
70
+ if email_column:
71
+ rows = [r for r in rows if r.get(email_column)]
72
+ if problems or not rows:
73
+ return {"subject": subject, "html_body": html_body, "problems": problems, "recipient": None}
74
+ row = rows[index % len(rows)]
75
+ return {
76
+ "subject": substitute_placeholders(subject, row, columns),
77
+ "html_body": substitute_placeholders(html_body, row, columns, html=True),
78
+ "problems": [],
79
+ "recipient": row.get(email_column) if email_column else None,
80
+ }
81
+
82
+
83
+ def _recipient_rows(
84
+ org_id: str, database_id: str, database: dict, segment: list[dict] | None, email_column: str | None = None,
85
+ ) -> list[dict]:
86
+ rows = databases.list_rows(org_id, database_id)
87
+ if segment:
88
+ rows = databases.apply_segment(rows, database["columns"], segment)
89
+ email_column = _email_column(database, email_column)
90
+ return [r for r in rows if email_column and r.get(email_column)]
91
+
92
+
93
+ def _certificates_for_organisations(org_id: str) -> None:
94
+ """Certificates are for organisation accounts. An individual's workspace is a personal org."""
95
+ if orgs.get_org(org_id).get("kind") == "personal":
96
+ raise orgs.PermissionError_("Certificates are for organisation accounts")
97
+
98
+
99
+ def preview_certificate(
100
+ org_id: str, database_id: str, certificate: dict, segment: list[dict] | None = None, index: int = 0,
101
+ email_column: str | None = None,
102
+ ) -> dict:
103
+ """The certificate recipient number `index` would get, as a scaled-down PNG, so the
104
+ composer shows the real generated file rather than an approximation."""
105
+ _certificates_for_organisations(org_id)
106
+ spec = certificates.parse_spec(certificate)
107
+ database = databases.get_database(org_id, database_id)
108
+ email_column = _email_column(database, email_column)
109
+ rows = _recipient_rows(org_id, database_id, database, segment, email_column)
110
+ if rows:
111
+ row = rows[index % len(rows)]
112
+ text = certificates.text_for(spec, row, database["columns"])
113
+ recipient = row.get(email_column)
114
+ else:
115
+ text, recipient = spec.text, None
116
+ return {"recipient": recipient, "text": text, "image_b64": base64.b64encode(certificates.preview_png(spec, text)).decode()}
117
+
118
+
119
+ def _email_column(database: dict, chosen: str | None = None) -> str | None:
120
+ """The column whose addresses are sent to: `chosen` when given (a list can hold more than
121
+ one email column, such as a guest's address and the staff member who checked them in),
122
+ otherwise the first email column."""
123
+ emails = [col["name"] for col in database["columns"] if col["type"] == "email"]
124
+ if chosen:
125
+ if chosen not in emails:
126
+ raise ValueError(f"{chosen!r} is not an email column in this list")
127
+ return chosen
128
+ return emails[0] if emails else None
129
+
130
+
131
+ ACTIVE = ("queued", "sending")
132
+ _locks: dict[tuple[str, str], threading.Lock] = {}
133
+
134
+
135
+ def _parse_when(value: str) -> datetime:
136
+ try:
137
+ when = datetime.fromisoformat(value.replace("Z", "+00:00"))
138
+ except (ValueError, AttributeError) as exc:
139
+ raise ValueError("That date and time could not be read") from exc
140
+ return when if when.tzinfo else when.replace(tzinfo=timezone.utc)
141
+
142
+
143
+ def clean_window(window: dict | None, default_timezone: str = "UTC") -> dict | None:
144
+ """A sending window: only send between `start` and `end` (HH:MM) on the given weekdays
145
+ (0 is Monday), in the given time zone. None means no restriction."""
146
+ if not window:
147
+ return None
148
+ from zoneinfo import ZoneInfo
149
+ try:
150
+ start, end = str(window["start"]), str(window["end"])
151
+ for value in (start, end):
152
+ datetime.strptime(value, "%H:%M")
153
+ days = sorted({int(d) for d in window.get("days", range(7))})
154
+ zone = str(window.get("timezone") or default_timezone or "UTC")
155
+ ZoneInfo(zone)
156
+ except Exception as exc:
157
+ raise ValueError("The sending window is not valid") from exc
158
+ if start >= end:
159
+ raise ValueError("The sending window must end after it starts")
160
+ if not days or any(d < 0 or d > 6 for d in days):
161
+ raise ValueError("Choose at least one day for the sending window")
162
+ return {"start": start, "end": end, "days": days, "timezone": zone}
163
+
164
+
165
+ def _in_window(window: dict | None, now: datetime) -> bool:
166
+ if not window:
167
+ return True
168
+ from zoneinfo import ZoneInfo
169
+ local = now.astimezone(ZoneInfo(window["timezone"]))
170
+ return local.weekday() in window["days"] and window["start"] <= local.strftime("%H:%M") < window["end"]
171
+
172
+
173
+ def _payload_path(org_id: str, send_id: str) -> str:
174
+ return f"orgs/{org_id}/send_payloads/{send_id}"
175
+
176
+
177
+ def _active_path(org_id: str, send_id: str) -> str:
178
+ return f"active_sends/{org_id}__{send_id}"
179
+
180
+
181
+ def _set_active(org_id: str, send_id: str, active: bool) -> None:
182
+ if active:
183
+ db.set_doc(_active_path(org_id, send_id), {"org_id": org_id, "send_id": send_id})
184
+ else:
185
+ db.delete_doc(_active_path(org_id, send_id))
186
+
187
+
188
+ def send_campaign(
189
+ org_id: str,
190
+ actor_uid: str,
191
+ subject: str,
192
+ html_body: str,
193
+ mailbox_connection_id: str,
194
+ database_id: str,
195
+ segment: list[dict] | None = None,
196
+ attachments: list[dict] | None = None,
197
+ certificate: dict | None = None,
198
+ email_column: str | None = None,
199
+ mode: str | None = None,
200
+ design: dict | None = None,
201
+ scheduled_at: str | None = None,
202
+ window: dict | None = None,
203
+ ) -> str:
204
+ """Queues the campaign and sends what can go now: `queue_campaign` followed by
205
+ `process_send`. A request handler calls queue_campaign and hands process_send to a
206
+ background task so the page does not wait; this does both in one go."""
207
+ send_id = queue_campaign(
208
+ org_id, actor_uid, subject, html_body, mailbox_connection_id, database_id, segment,
209
+ attachments, certificate, email_column, mode, design, scheduled_at, window,
210
+ )
211
+ process_send(org_id, send_id)
212
+ return send_id
213
+
214
+
215
+ def queue_campaign(
216
+ org_id: str,
217
+ actor_uid: str,
218
+ subject: str,
219
+ html_body: str,
220
+ mailbox_connection_id: str,
221
+ database_id: str,
222
+ segment: list[dict] | None = None,
223
+ attachments: list[dict] | None = None,
224
+ certificate: dict | None = None,
225
+ email_column: str | None = None,
226
+ mode: str | None = None,
227
+ design: dict | None = None,
228
+ scheduled_at: str | None = None,
229
+ window: dict | None = None,
230
+ only_row_ids: list[str] | None = None,
231
+ automated: bool = False,
232
+ ) -> str:
233
+ """Saves a campaign to send to every row in `database_id` that has a value in its
234
+ email-typed column, substituting that row's own values into {Placeholder} tokens first.
235
+ `segment`, if given, is a list of {field, op, value} conditions (ANDed, see
236
+ databases.apply_segment) that narrows the recipient list before the email-column check —
237
+ the same predicate the Campaigns page's live "N recipients" preview runs, so what you
238
+ previewed is exactly who gets sent to. Raises ValueError if the mailbox isn't verified or
239
+ the database has no column classified as "email" (set one via databases.update_column_type
240
+ first).
241
+
242
+ `attachments` ([{filename, content_type, data_b64}]) go to every recipient as they are.
243
+ `certificate` (see backend/certificates.parse_spec) adds one generated file per recipient,
244
+ with that recipient's own values drawn onto the image. Images uploaded into the message
245
+ travel as inline parts (backend/email_parts.extract_inline_images).
246
+
247
+ `scheduled_at` (an ISO date-time) holds the send until then; `window` limits sending to
248
+ certain hours and days (see clean_window). The send is carried out by process_send, which
249
+ keeps to the mailbox's daily limit and the organisation's hourly cap by sending what fits
250
+ and continuing when room opens up.
251
+
252
+ `only_row_ids` narrows the send to those rows (a welcome email goes to the one new person).
253
+ `automated` is for mail the system sends on a member's earlier say-so, such as a form's
254
+ welcome email: no one is signed in then, so the permission check is skipped."""
255
+ if not automated:
256
+ orgs.require_permission(org_id, actor_uid, "send")
257
+ if certificate:
258
+ _certificates_for_organisations(org_id)
259
+
260
+ connection = mailboxes.get_mailbox(org_id, mailbox_connection_id)
261
+ if connection["status"] != "verified":
262
+ raise ValueError(
263
+ f"Mailbox connection {mailbox_connection_id!r} is {connection['status']!r}, "
264
+ f"not verified — it can't be used to send"
265
+ )
266
+
267
+ database = databases.get_database(org_id, database_id)
268
+ email_column = _email_column(database, email_column)
269
+ if email_column is None:
270
+ raise ValueError(
271
+ f"Database {database_id!r} has no column classified as an email address — "
272
+ f"set one via Manage columns before sending"
273
+ )
274
+
275
+ problems = _template_problems(subject, html_body, database["columns"])
276
+ if problems:
277
+ raise ValueError("The message cannot be sent: " + "; ".join(problems))
278
+
279
+ # Checked now so a bad attachment or image fails the request, not the background send.
280
+ email_parts.decode_attachments(attachments)
281
+ spec = certificates.parse_spec(certificate) if certificate else None
282
+ email_parts.extract_inline_images(html_body)
283
+
284
+ if scheduled_at:
285
+ scheduled_at = _parse_when(scheduled_at).isoformat()
286
+ window = clean_window(window, (orgs.get_org(org_id).get("timezone") or "UTC"))
287
+
288
+ rows = _recipient_rows(org_id, database_id, database, segment, email_column)
289
+ if only_row_ids is not None:
290
+ rows = [r for r in rows if r["row_id"] in only_row_ids]
291
+ brand = brands.brand_for_mailbox(org_id, mailbox_connection_id) or {}
292
+ # The HTML as written (inline images still in place), so the details page shows it whole.
293
+ message_id = messages.create_message(
294
+ 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,
295
+ )
296
+ return _enqueue(
297
+ org_id, actor_uid, message_id=message_id, subject=subject, html_body=html_body,
298
+ mailbox_connection_id=mailbox_connection_id, from_email=connection.get("email"), brand_id=brand.get("brand_id"),
299
+ database_id=database_id, email_column=email_column, segment=segment or [], row_ids=[r["row_id"] for r in rows],
300
+ attachments=attachments, certificate=certificate if spec else None, attachment_names=[a.get("filename") for a in attachments or []],
301
+ scheduled_at=scheduled_at, window=window,
302
+ )
303
+
304
+
305
+ def _enqueue(org_id: str, actor_uid: str, *, row_ids: list[str], html_body: str, attachments: list[dict] | None, certificate: dict | None, **fields) -> str:
306
+ send_id = uuid.uuid4().hex
307
+ created = _now()
308
+ db.set_doc(_payload_path(org_id, send_id), {"html_body": html_body, "attachments": attachments or [], "certificate": certificate})
309
+ db.set_doc(
310
+ _send_path(org_id, send_id),
311
+ {
312
+ **fields,
313
+ "certificate": certificate is not None,
314
+ "created_by": actor_uid,
315
+ "created_at": created,
316
+ "sent_at": fields.get("scheduled_at") or created,
317
+ "status": "queued",
318
+ "note": "",
319
+ "pending": row_ids,
320
+ "total": len(row_ids),
321
+ "per_recipient": {},
322
+ },
323
+ )
324
+ _set_active(org_id, send_id, True)
325
+ return send_id
326
+
327
+
328
+ def process_send(org_id: str, send_id: str, now: datetime | None = None, budget_seconds: float | None = None) -> dict:
329
+ """Sends what can go right now for one queued send, then returns its record. Safe to call
330
+ at any time and from several places: it does nothing unless the send is due, inside its
331
+ window, within the mailbox's daily limit and the organisation's hourly cap, and only one
332
+ caller works on a send at once. The rest stays queued for the next call."""
333
+ lock = _locks.setdefault((org_id, send_id), threading.Lock())
334
+ if not lock.acquire(blocking=False):
335
+ return get_send(org_id, send_id)
336
+ try:
337
+ return _process(org_id, send_id, now or datetime.now(timezone.utc), budget_seconds)
338
+ finally:
339
+ lock.release()
340
+
341
+
342
+ def _process(org_id: str, send_id: str, now: datetime, budget_seconds: float | None) -> dict:
343
+ send = get_send(org_id, send_id)
344
+ if send.get("status") not in ACTIVE:
345
+ return send
346
+ if send.get("scheduled_at") and _parse_when(send["scheduled_at"]) > now:
347
+ return send
348
+ stamp = now.isoformat()
349
+ pending: list[str] = list(send.get("pending", []))
350
+ if not pending:
351
+ return _finish(org_id, send_id, send)
352
+ if not _in_window(send.get("window"), now):
353
+ return _note(org_id, send_id, send, "Waiting for the sending window to open.")
354
+
355
+ try:
356
+ connection = mailboxes.get_mailbox(org_id, send["mailbox_connection_id"])
357
+ database = databases.get_database(org_id, send["database_id"])
358
+ except orgs.NotFoundError:
359
+ return _stop(org_id, send_id, send, "paused", "The mailbox or the list for this send was removed. Resume after restoring it, or cancel.")
360
+ if connection["status"] != "verified":
361
+ return _stop(org_id, send_id, send, "paused", "The mailbox is not working. Fix it in Settings, then resume.")
362
+
363
+ box = mailboxes.mailbox_settings(connection)
364
+ room = len(pending)
365
+ reason = ""
366
+ if box["daily_limit"]:
367
+ left = max(box["daily_limit"] - sent_today(org_id, send["mailbox_connection_id"], now), 0)
368
+ if left < room:
369
+ room, reason = left, f"The mailbox's daily limit of {box['daily_limit']} is reached. Sending continues tomorrow."
370
+ hourly = rate_limiter.remaining_capacity(org_id)
371
+ if hourly < room:
372
+ room, reason = hourly, "Waiting for the hourly sending limit. Sending continues as room opens up."
373
+ if room <= 0:
374
+ return _note(org_id, send_id, send, reason)
375
+ rate_limiter.check_and_consume(org_id, room)
376
+
377
+ payload = db.get_doc(_payload_path(org_id, send_id)) or {}
378
+ shared_files = email_parts.decode_attachments(payload.get("attachments"))
379
+ spec = certificates.parse_spec(payload["certificate"]) if payload.get("certificate") else None
380
+ html_body, inline_images = email_parts.extract_inline_images(payload.get("html_body", ""))
381
+ rows = {r["row_id"]: r for r in databases.list_rows(org_id, send["database_id"])}
382
+ columns = database["columns"]
383
+ email_column = send.get("email_column")
384
+ try:
385
+ email_column = _email_column(database, email_column)
386
+ except ValueError: # renamed or retyped since the send was queued
387
+ email_column = _email_column(database)
388
+ blocked = unsubscribe.suppressed(org_id)
389
+
390
+ brand = brands.brand_for_mailbox(org_id, send["mailbox_connection_id"]) or {}
391
+ prefs = settings.email_settings(org_id)
392
+ credentials = mailboxes.get_decrypted_credentials(org_id, send["mailbox_connection_id"])
393
+ try:
394
+ mailer = mailer_client.get_mailer(connection["kind"], credentials)
395
+ except (AuthError, ConnectionFailure, OSError) as exc:
396
+ # The mailbox's server can't be reached right now. Keep the queue and try again on the
397
+ # next run instead of failing the whole background run.
398
+ log.warning("Could not open the mailbox for send %s: %s", send_id, exc)
399
+ return _note(org_id, send_id, send, f"Could not reach the mailbox's server ({exc}). M8ion will try again shortly.")
400
+ if hasattr(mailer, "configure"):
401
+ mailer.configure(
402
+ box["from_name"] or brand.get("from_name") or prefs["from_name"],
403
+ box["reply_to"] or brand.get("reply_to") or prefs["reply_to"],
404
+ prefs["save_sent_copy"] if box["save_sent_copy"] is None else box["save_sent_copy"],
405
+ )
406
+
407
+ per_recipient = dict(send.get("per_recipient", {}))
408
+ started = time.monotonic()
409
+ sent_now = 0
410
+ status = "sending"
411
+ save_every = 10
412
+
413
+ def save(final: bool = False) -> None:
414
+ # The status is only written at the end, so a pause pressed meanwhile is not overwritten.
415
+ update = {"pending": pending, "per_recipient": per_recipient, "note": reason}
416
+ if final:
417
+ update["status"] = status
418
+ db.update_doc(_send_path(org_id, send_id), update)
419
+
420
+ while pending and sent_now < room:
421
+ row_id = pending[0]
422
+ row = rows.get(row_id)
423
+ address = row.get(email_column) if row and email_column else None
424
+ if row is None or not address:
425
+ per_recipient[row_id] = {"status": "skipped", "error": "No longer in the list", "at": stamp}
426
+ elif address.strip().lower() in blocked:
427
+ per_recipient[row_id] = {"status": "skipped", "error": "Unsubscribed", "at": stamp}
428
+ else:
429
+ if sent_now and prefs["pause_seconds"]:
430
+ time.sleep(prefs["pause_seconds"])
431
+ files = list(shared_files)
432
+ try:
433
+ if spec is not None:
434
+ files.append(certificates.attachment_for(spec, row, columns))
435
+ reference = mailer.send(
436
+ to_addr=address,
437
+ subject=substitute_placeholders(send["subject"], row, columns),
438
+ body=substitute_placeholders(html_body, row, columns, html=True) + unsubscribe.footer_html(org_id, address, send.get("from_email") or ""),
439
+ attachments=files, inline_images=inline_images, headers=unsubscribe.headers(org_id, address, send.get("from_email") or ""),
440
+ )
441
+ # "sent" means the mailbox's own server accepted the message. Whether it then
442
+ # reached the inbox is only known from bounces (Phase 2); the Message-ID lets the
443
+ # hosting provider trace a message in their logs.
444
+ per_recipient[row_id] = {"status": "sent", "error": None, "at": stamp}
445
+ if isinstance(reference, str):
446
+ per_recipient[row_id]["reference"] = reference
447
+ except (AuthError, ConnectionFailure, OSError) as exc:
448
+ per_recipient[row_id] = {"status": "failed", "error": str(exc), "at": stamp}
449
+ sent_now += 1
450
+ pending.pop(0)
451
+ if len(per_recipient) % save_every == 0:
452
+ save()
453
+ # A pause or cancel pressed while this runs takes effect within a few emails.
454
+ if (db.get_doc(_send_path(org_id, send_id)) or {}).get("status") not in ACTIVE:
455
+ break
456
+ if budget_seconds is not None and time.monotonic() - started > budget_seconds:
457
+ reason = "Sending continues on the next run."
458
+ break
459
+ if hasattr(mailer, "close"):
460
+ mailer.close()
461
+
462
+ current = (db.get_doc(_send_path(org_id, send_id)) or {}).get("status")
463
+ if current not in ACTIVE: # paused or cancelled while sending: keep that, save the progress
464
+ status = current
465
+ elif not pending:
466
+ status = "done"
467
+ reason = ""
468
+ elif not reason and sent_now >= room:
469
+ reason = "Sending continues shortly."
470
+ save(final=True)
471
+ if sent_now:
472
+ delivery.watch(org_id, send_id) # look for delays, bounces and replies over the next days
473
+ if status not in ACTIVE:
474
+ _set_active(org_id, send_id, False)
475
+ return get_send(org_id, send_id)
476
+
477
+
478
+ def _note(org_id: str, send_id: str, send: dict, note: str) -> dict:
479
+ if send.get("note") != note:
480
+ db.update_doc(_send_path(org_id, send_id), {"note": note})
481
+ return send | {"note": note}
482
+
483
+
484
+ def _stop(org_id: str, send_id: str, send: dict, status: str, note: str) -> dict:
485
+ db.update_doc(_send_path(org_id, send_id), {"status": status, "note": note})
486
+ _set_active(org_id, send_id, False)
487
+ return send | {"status": status, "note": note}
488
+
489
+
490
+ def _finish(org_id: str, send_id: str, send: dict) -> dict:
491
+ db.update_doc(_send_path(org_id, send_id), {"status": "done", "note": ""})
492
+ _set_active(org_id, send_id, False)
493
+ return send | {"status": "done", "note": ""}
494
+
495
+
496
+ def run_due(now: datetime | None = None, budget_seconds: float = 240) -> dict:
497
+ """Carries out every active send that is due. A timer calls this every minute or so (Cloud
498
+ Scheduler in production, a small thread when running locally); each run does a bounded
499
+ amount of work and exits."""
500
+ started = time.monotonic()
501
+ checked = 0
502
+ for doc in list(db.query_prefix("active_sends/").values()):
503
+ left = budget_seconds - (time.monotonic() - started)
504
+ if left <= 0:
505
+ break
506
+ try:
507
+ process_send(doc["org_id"], doc["send_id"], now, left)
508
+ except orgs.NotFoundError:
509
+ _set_active(doc["org_id"], doc["send_id"], False)
510
+ checked += 1
511
+ return {"checked": checked}
512
+
513
+
514
+ def control_send(org_id: str, actor_uid: str, send_id: str, action: str) -> dict:
515
+ """Pause, resume or cancel a send that has not finished."""
516
+ orgs.require_permission(org_id, actor_uid, "send")
517
+ send = get_send(org_id, send_id)
518
+ status = send.get("status", "done")
519
+ if action == "pause" and status in ACTIVE:
520
+ update = {"status": "paused", "note": "Paused."}
521
+ elif action == "resume" and status == "paused":
522
+ update = {"status": "queued", "note": ""}
523
+ elif action == "cancel" and status in ACTIVE + ("paused",):
524
+ update = {"status": "cancelled", "note": "Cancelled."}
525
+ else:
526
+ 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")
527
+ db.update_doc(_send_path(org_id, send_id), update)
528
+ _set_active(org_id, send_id, update["status"] == "queued")
529
+ return get_send(org_id, send_id)
530
+
531
+
532
+ def sent_today(org_id: str, mailbox_connection_id: str, now: datetime | None = None) -> int:
533
+ """Emails this mailbox's server accepted since midnight UTC."""
534
+ today = (now or datetime.now(timezone.utc)).astimezone(timezone.utc).date().isoformat()
535
+ total = 0
536
+ for send in db.query_prefix(f"orgs/{org_id}/sends/").values():
537
+ if send.get("mailbox_connection_id") != mailbox_connection_id:
538
+ continue
539
+ for r in send["per_recipient"].values():
540
+ if r["status"] == "sent" and str(r.get("at") or send.get("sent_at", "")).startswith(today):
541
+ total += 1
542
+ return total
543
+
544
+
545
+ def get_send(org_id: str, send_id: str) -> dict:
546
+ doc = db.get_doc(_send_path(org_id, send_id))
547
+ if doc is None:
548
+ raise orgs.NotFoundError(f"No send {send_id!r} in org {org_id!r}")
549
+ return doc
550
+
551
+
552
+ def list_sends(org_id: str, actor_uid: str, limit: int = 50) -> list[dict]:
553
+ """Recent sends, newest first, with counts instead of the per-recipient map."""
554
+ orgs.require_permission(org_id, actor_uid)
555
+ prefix = f"orgs/{org_id}/sends/"
556
+ out = []
557
+ for path, doc in db.query_prefix(prefix).items():
558
+ statuses = [r.get("status") for r in (doc.get("per_recipient") or {}).values()]
559
+ subject = doc.get("subject")
560
+ if subject is None and doc.get("message_id"):
561
+ try:
562
+ subject = messages.get_message(org_id, doc["message_id"])["subject"]
563
+ except orgs.NotFoundError:
564
+ subject = ""
565
+ out.append({
566
+ "send_id": path[len(prefix):],
567
+ "subject": subject or "",
568
+ "database_id": doc.get("database_id"),
569
+ "mailbox_connection_id": doc.get("mailbox_connection_id"),
570
+ "sent_at": doc.get("sent_at"),
571
+ "sent": statuses.count("sent"),
572
+ "failed": statuses.count("failed"),
573
+ "skipped": statuses.count("skipped"),
574
+ "pending": len(doc.get("pending") or []),
575
+ "status": doc.get("status", "done"),
576
+ "scheduled_at": doc.get("scheduled_at"),
577
+ "note": doc.get("note", ""),
578
+ "attachment_names": doc.get("attachment_names", []),
579
+ "certificate": bool(doc.get("certificate")),
580
+ })
581
+ out.sort(key=lambda s: s["sent_at"] or "", reverse=True)
582
+ return out[:limit]
583
+
584
+
585
+ def get_send_details(org_id: str, actor_uid: str, send_id: str) -> dict:
586
+ """Everything about one send for its details page: who it went to (addresses looked up from
587
+ the list now, since the send record keeps row ids only), how each went, where it came from,
588
+ and the email itself so it can be read again or saved as a preset."""
589
+ orgs.require_permission(org_id, actor_uid)
590
+ send = get_send(org_id, send_id)
591
+ try:
592
+ message = messages.get_message(org_id, send["message_id"])
593
+ except (orgs.NotFoundError, KeyError):
594
+ message = {}
595
+
596
+ database = None
597
+ try:
598
+ database = databases.get_database(org_id, send["database_id"])
599
+ except orgs.NotFoundError:
600
+ pass
601
+ addresses: dict[str, str] = {}
602
+ column = send.get("email_column")
603
+ if database is not None:
604
+ try:
605
+ column = _email_column(database, column)
606
+ except ValueError: # the column was renamed or retyped since
607
+ column = _email_column(database)
608
+ if column:
609
+ addresses = {r["row_id"]: str(r.get(column) or "") for r in databases.list_rows(org_id, send["database_id"])}
610
+
611
+ try:
612
+ mailbox_email = mailboxes.get_mailbox(org_id, send["mailbox_connection_id"]).get("email")
613
+ except (orgs.NotFoundError, KeyError):
614
+ mailbox_email = send.get("from_email")
615
+
616
+ try:
617
+ tracking = bool(mailboxes.get_mailbox(org_id, send["mailbox_connection_id"]).get("has_imap"))
618
+ except (orgs.NotFoundError, KeyError):
619
+ tracking = False
620
+ recipients = [
621
+ {
622
+ "row_id": row_id,
623
+ "address": addresses.get(row_id) or None,
624
+ "status": r.get("status"),
625
+ "error": r.get("error"),
626
+ "reference": r.get("reference"),
627
+ "delivery": delivery.shown_state(r, tracking=tracking),
628
+ }
629
+ for row_id, r in (send.get("per_recipient") or {}).items()
630
+ ]
631
+ waiting = "queued" if send.get("status") in ACTIVE + ("paused",) else "not sent"
632
+ recipients += [
633
+ {"row_id": row_id, "address": addresses.get(row_id) or None, "status": waiting, "error": None, "reference": None, "delivery": delivery.shown_state({"status": waiting})}
634
+ for row_id in send.get("pending") or []
635
+ ]
636
+ recipients.sort(key=lambda r: (r["status"] != "failed", (r["address"] or "~").lower()))
637
+ return {
638
+ "send_id": send_id,
639
+ "subject": send.get("subject") or message.get("subject") or "",
640
+ "sent_at": send.get("sent_at"),
641
+ "status": send.get("status", "done"),
642
+ "note": send.get("note", ""),
643
+ "scheduled_at": send.get("scheduled_at"),
644
+ "window": send.get("window"),
645
+ "from_email": mailbox_email,
646
+ "database_id": send.get("database_id"),
647
+ "database_name": database.get("name") if database else None,
648
+ "email_column": column,
649
+ "segment": send.get("segment") or [],
650
+ "attachment_names": send.get("attachment_names", []),
651
+ "certificate": bool(send.get("certificate")),
652
+ "recipients": recipients,
653
+ "html_body": message.get("html_body", ""),
654
+ "mode": message.get("mode") or "html",
655
+ "design": message.get("design"),
656
+ }
backend/settings.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Settings, in two scopes:
3
+
4
+ - Personal (per person, per org): the name shown in the console and which notices they want.
5
+ Any member edits their own.
6
+ - Organisation: the org's name (owner or admin) and how its emails go out (operator or above):
7
+ the sender name beside the address, a reply-to address, the mailbox the composer picks by
8
+ default, and whether a copy of each email is filed in the mailbox's Sent folder.
9
+
10
+ Defaults live here, so a setting nobody has touched still reads as a full set of values.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import re
16
+ from datetime import datetime, timezone
17
+
18
+ from backend import firestore_client as db
19
+ from backend import mailboxes, orgs
20
+
21
+ _EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
22
+ _MAX_NAME = 80
23
+
24
+ NOTIFICATION_KEYS = ("campaign_finished", "emails_turned_away", "mailbox_problem", "new_signup", "weekly_summary")
25
+ DEFAULT_NOTIFICATIONS = {
26
+ "campaign_finished": False,
27
+ "emails_turned_away": True,
28
+ "mailbox_problem": True,
29
+ "new_signup": False,
30
+ "weekly_summary": False,
31
+ }
32
+ DEFAULT_EMAILS = {"from_name": "", "reply_to": "", "default_mailbox_id": "", "save_sent_copy": True, "pause_seconds": 2}
33
+ # Seconds M8ion waits between two emails of a campaign. Some mail servers accept a fast burst and
34
+ # then never deliver it, so campaigns are spaced out unless the organisation turns this down.
35
+ MAX_PAUSE_SECONDS = 30
36
+ ORG_PROFILE_FIELDS = ("website", "domain", "country", "state", "lga", "address", "postal_code", "timezone")
37
+ _DOMAIN_RE = re.compile(r"^(?=.{3,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$")
38
+
39
+
40
+ def _now() -> str:
41
+ return datetime.now(timezone.utc).isoformat()
42
+
43
+
44
+ def _personal_path(org_id: str, uid: str) -> str:
45
+ return f"orgs/{org_id}/personal_settings/{uid}"
46
+
47
+
48
+ def _emails_path(org_id: str) -> str:
49
+ return f"orgs/{org_id}/settings/emails"
50
+
51
+
52
+ def _clean_name(value: str, what: str) -> str:
53
+ value = " ".join(str(value or "").split())
54
+ if len(value) > _MAX_NAME:
55
+ raise ValueError(f"Keep the {what} to {_MAX_NAME} characters or fewer")
56
+ return value
57
+
58
+
59
+ def get_settings(org_id: str, uid: str) -> dict:
60
+ """Everything the Settings pages show, with defaults filled in."""
61
+ role = orgs.require_permission(org_id, uid)
62
+ permissions = sorted(orgs.permissions_for(org_id, role))
63
+ personal = db.get_doc(_personal_path(org_id, uid)) or {}
64
+ return {
65
+ "role": role,
66
+ "permissions": permissions,
67
+ "profile": profile_of(org_id, uid, personal),
68
+ "organisation": organisation(org_id),
69
+ "notifications": DEFAULT_NOTIFICATIONS | {k: bool(v) for k, v in (personal.get("notifications") or {}).items() if k in NOTIFICATION_KEYS},
70
+ "emails": email_settings(org_id),
71
+ }
72
+
73
+
74
+ def email_settings(org_id: str) -> dict:
75
+ """How the org's emails go out. Read by the send itself, so it takes no actor."""
76
+ return DEFAULT_EMAILS | {k: v for k, v in (db.get_doc(_emails_path(org_id)) or {}).items() if k in DEFAULT_EMAILS}
77
+
78
+
79
+ PROFILE_EXTRAS = ("job_title", "phone", "about")
80
+
81
+
82
+ def profile_of(org_id: str, uid: str, personal: dict | None = None) -> dict:
83
+ """The person's own profile: what they chose to share, plus facts about their use of this organisation."""
84
+ personal = personal if personal is not None else (db.get_doc(_personal_path(org_id, uid)) or {})
85
+ member = db.get_doc(f"orgs/{org_id}/members/{uid}") or {}
86
+ sends = [d for d in db.query_prefix(f"orgs/{org_id}/sends/").values() if d.get("created_by") == uid]
87
+ return {
88
+ "display_name": personal.get("display_name", ""),
89
+ **{k: personal.get(k, "") for k in PROFILE_EXTRAS},
90
+ "active_since": member.get("added_at"),
91
+ "campaigns_sent": len(sends),
92
+ "last_active": max((d.get("created_at") or "" for d in sends), default="") or None,
93
+ }
94
+
95
+
96
+ def update_profile(org_id: str, uid: str, display_name: str, extras: dict | None = None) -> dict:
97
+ orgs.require_permission(org_id, uid)
98
+ name = _clean_name(display_name, "name")
99
+ update = {"display_name": name}
100
+ for key in PROFILE_EXTRAS:
101
+ if extras and key in extras:
102
+ limit = 500 if key == "about" else 80
103
+ value = " ".join(str(extras[key] or "").split()) if key != "about" else str(extras[key] or "").strip()
104
+ if len(value) > limit:
105
+ raise ValueError(f"Keep this to {limit} characters or fewer")
106
+ update[key] = value
107
+ _merge(_personal_path(org_id, uid), update)
108
+ return profile_of(org_id, uid)
109
+
110
+
111
+ def update_notifications(org_id: str, uid: str, values: dict) -> dict:
112
+ orgs.require_permission(org_id, uid)
113
+ unknown = set(values) - set(NOTIFICATION_KEYS)
114
+ if unknown:
115
+ raise ValueError(f"Unknown notice: {', '.join(sorted(unknown))}")
116
+ current = get_settings(org_id, uid)["notifications"] | {k: bool(v) for k, v in values.items()}
117
+ _merge(_personal_path(org_id, uid), {"notifications": current})
118
+ return current
119
+
120
+
121
+ def organisation(org_id: str) -> dict:
122
+ org = orgs.get_org(org_id)
123
+ profile = org.get("profile") or {}
124
+ return {"name": org["name"], **{k: profile.get(k, "") for k in ORG_PROFILE_FIELDS}}
125
+
126
+
127
+ def rename_org(org_id: str, uid: str, name: str, profile: dict | None = None) -> dict:
128
+ """Saves the org's name and its details: website, main domain, country, state, LGA, postal
129
+ address and postal code (many countries' email laws ask for one in marketing emails) and time zone."""
130
+ orgs.require_permission(org_id, uid, "manage_settings")
131
+ name = _clean_name(name, "organisation name")
132
+ if not name:
133
+ raise ValueError("Give the organisation a name")
134
+ update: dict = {"name": name}
135
+ if profile is not None:
136
+ unknown = set(profile) - set(ORG_PROFILE_FIELDS)
137
+ if unknown:
138
+ raise ValueError(f"Unknown organisation detail: {', '.join(sorted(unknown))}")
139
+ clean = {k: " ".join(str(profile.get(k) or "").split()) for k in ORG_PROFILE_FIELDS}
140
+ if len(clean["address"]) > 300:
141
+ raise ValueError("Keep the address to 300 characters or fewer")
142
+ if len(clean["postal_code"]) > 20:
143
+ raise ValueError("Keep the postal code to 20 characters or fewer")
144
+ for key in ("country", "state", "lga"):
145
+ if len(clean[key]) > 100:
146
+ raise ValueError(f"Keep the {key} to 100 characters or fewer")
147
+ clean["domain"] = clean["domain"].lower().removeprefix("https://").removeprefix("http://").removeprefix("www.").rstrip("/")
148
+ if clean["domain"] and not _DOMAIN_RE.match(clean["domain"]):
149
+ raise ValueError("Enter a domain like yourcompany.com")
150
+ if clean["website"] and not clean["website"].startswith(("https://", "http://")):
151
+ clean["website"] = "https://" + clean["website"]
152
+ if clean["timezone"]:
153
+ try:
154
+ from zoneinfo import ZoneInfo
155
+ ZoneInfo(clean["timezone"])
156
+ except Exception as exc: # noqa: BLE001
157
+ raise ValueError("Pick a time zone from the list") from exc
158
+ update["profile"] = clean
159
+ db.update_doc(f"orgs/{org_id}", update)
160
+ return organisation(org_id)
161
+
162
+
163
+ def update_emails(org_id: str, uid: str, values: dict) -> dict:
164
+ orgs.require_permission(org_id, uid, "manage_settings")
165
+ unknown = set(values) - set(DEFAULT_EMAILS)
166
+ if unknown:
167
+ raise ValueError(f"Unknown email setting: {', '.join(sorted(unknown))}")
168
+ clean: dict = {}
169
+ if "from_name" in values:
170
+ clean["from_name"] = _clean_name(values["from_name"], "sender name").replace('"', "")
171
+ if "reply_to" in values:
172
+ reply_to = str(values["reply_to"] or "").strip()
173
+ if reply_to and not _EMAIL_RE.match(reply_to):
174
+ raise ValueError("The reply-to address does not look like an email address")
175
+ clean["reply_to"] = reply_to
176
+ if "default_mailbox_id" in values:
177
+ mailbox_id = str(values["default_mailbox_id"] or "")
178
+ if mailbox_id:
179
+ mailboxes.get_mailbox(org_id, mailbox_id) # raises NotFoundError for another org's id
180
+ clean["default_mailbox_id"] = mailbox_id
181
+ if "save_sent_copy" in values:
182
+ clean["save_sent_copy"] = bool(values["save_sent_copy"])
183
+ if "pause_seconds" in values:
184
+ try:
185
+ pause = float(values["pause_seconds"] or 0)
186
+ except (TypeError, ValueError) as exc:
187
+ raise ValueError("The pause must be a number of seconds") from exc
188
+ if not 0 <= pause <= MAX_PAUSE_SECONDS:
189
+ raise ValueError(f"The pause must be between 0 and {MAX_PAUSE_SECONDS} seconds")
190
+ clean["pause_seconds"] = pause
191
+ _merge(_emails_path(org_id), clean)
192
+ return email_settings(org_id)
193
+
194
+
195
+ def _merge(path: str, values: dict) -> None:
196
+ doc = db.get_doc(path) or {}
197
+ db.set_doc(path, doc | values | {"updated_at": _now()})
backend/smtp_mailer.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The real counterpart to backend/mock_mailer.py — same interface (`.send(to_addr, subject,
3
+ body)`, same AuthError/ConnectionFailure exceptions on connect), but an actual SMTP+STARTTLS
4
+ connection instead of an in-memory simulation. Only handles kind="smtp" connections (raw
5
+ host/port/username/password) — real OAuth sending needs a real Google Cloud OAuth app,
6
+ which doesn't exist yet (see docs/engineering/env-config-reference.md).
7
+
8
+ Reusing mock_mailer's exception classes (not defining new ones) is deliberate: every caller
9
+ that already catches AuthError/ConnectionFailure around a mailer call works unchanged
10
+ whether the mailer underneath is real or mocked.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import html
16
+ import imaplib
17
+ import logging
18
+ import re
19
+ import smtplib
20
+ import ssl
21
+ import time
22
+ from email import encoders
23
+ from email.mime.base import MIMEBase
24
+ from email.mime.image import MIMEImage
25
+ from email.mime.multipart import MIMEMultipart
26
+ from email.mime.text import MIMEText
27
+ from email.utils import formataddr, formatdate, make_msgid
28
+
29
+ from backend.delivery import imap_details
30
+ from backend.email_parts import Attachment, InlineImage
31
+ from backend.mock_mailer import AuthError, ConnectionFailure
32
+
33
+
34
+ # Port 465 is implicit TLS (the connection is SSL-wrapped from the first byte) — it must use
35
+ # SMTP_SSL, never SMTP()+starttls(), which assumes a plaintext handshake first. Mixing the two
36
+ # up doesn't raise a clean auth/protocol error, it just hangs until the socket times out, so an
37
+ # implicit-TLS host on 465 was silently indistinguishable from a genuinely unreachable one.
38
+ IMPLICIT_TLS_PORT = 465
39
+
40
+ log = logging.getLogger(__name__)
41
+
42
+
43
+ def clean_password(password: str) -> str:
44
+ """App passwords are shown in groups ("abcd efgh ijkl mnop") and get pasted with the
45
+ spaces, but the spaces are never part of the password, so they are ignored here."""
46
+ return "".join(password.split())
47
+
48
+
49
+ class SMTPMailer:
50
+ def __init__(self, credentials: dict):
51
+ host = credentials["host"]
52
+ port = credentials["port"]
53
+ username = credentials["username"].strip()
54
+ password = clean_password(credentials["password"])
55
+
56
+ # Phase 1: reach the server and secure the connection. A failure here really is
57
+ # "couldn't reach the server".
58
+ try:
59
+ if port == IMPLICIT_TLS_PORT:
60
+ self._server = smtplib.SMTP_SSL(host, port, timeout=15, context=ssl.create_default_context())
61
+ else:
62
+ self._server = smtplib.SMTP(host, port, timeout=15)
63
+ self._server.starttls(context=ssl.create_default_context())
64
+ self._server.ehlo()
65
+ except (smtplib.SMTPException, OSError) as exc:
66
+ log.warning("SMTP connection to %s:%s failed: %r", host, port, exc)
67
+ raise ConnectionFailure(str(exc)) from exc
68
+
69
+ # Phase 2: sign in. smtplib's login() retries every mechanism the server offers, and
70
+ # Gmail hangs up after the second rejected attempt, so a wrong password surfaced as
71
+ # SMTPServerDisconnected ("couldn't reach the server"). One mechanism gives the
72
+ # provider's real answer, and a hang-up during sign-in is treated as a rejection.
73
+ try:
74
+ if self._server.has_extn("auth") and "PLAIN" in self._server.esmtp_features["auth"].upper().split():
75
+ self._server.user, self._server.password = username, password
76
+ self._server.auth("PLAIN", self._server.auth_plain, initial_response_ok=True)
77
+ else:
78
+ self._server.login(username, password)
79
+ except (smtplib.SMTPAuthenticationError, smtplib.SMTPServerDisconnected) as exc:
80
+ log.warning("SMTP sign-in rejected by %s:%s for %s: %s", host, port, username, exc)
81
+ raise AuthError(str(exc)) from exc
82
+ except (smtplib.SMTPException, OSError) as exc:
83
+ log.warning("SMTP sign-in to %s:%s failed: %r", host, port, exc)
84
+ raise ConnectionFailure(str(exc)) from exc
85
+
86
+ self._from_addr = username
87
+ self._from_name = ""
88
+ self._reply_to = ""
89
+ self._sent_copy: SentCopy | None = SentCopy(host, username, password, imap=imap_details(credentials))
90
+
91
+ def configure(self, from_name: str = "", reply_to: str = "", save_sent_copy: bool = True) -> None:
92
+ """The org's email settings (backend/settings.py): the name shown beside the address,
93
+ where replies go, and whether a copy is filed in Sent."""
94
+ self._from_name, self._reply_to = from_name.strip(), reply_to.strip()
95
+ if not save_sent_copy and self._sent_copy is not None:
96
+ self._sent_copy.close()
97
+ self._sent_copy = None
98
+
99
+ def send(self, to_addr: str, subject: str, body: str,
100
+ attachments: list[Attachment] | None = None, inline_images: list[InlineImage] | None = None,
101
+ headers: dict[str, str] | None = None) -> str:
102
+ """Hands one message to the server and returns its Message-ID. Raises
103
+ ConnectionFailure when the server refuses it, including refusing the recipient."""
104
+ msg = build_message(body, attachments or [], inline_images or [])
105
+ msg["Subject"] = subject
106
+ from_name = getattr(self, "_from_name", "")
107
+ msg["From"] = formataddr((from_name, self._from_addr)) if from_name else self._from_addr
108
+ msg["To"] = to_addr
109
+ if getattr(self, "_reply_to", ""):
110
+ msg["Reply-To"] = self._reply_to
111
+ # Date and Message-ID are required by RFC 5322. Some servers add them on the way out,
112
+ # many hosting servers don't, and Gmail turns away mail that arrives without a
113
+ # Message-ID, so every message carries its own.
114
+ for name, value in (headers or {}).items():
115
+ msg[name] = value
116
+ msg["Date"] = formatdate(usegmt=True)
117
+ msg["Message-ID"] = make_msgid(domain=self._from_addr.rpartition("@")[2] or None)
118
+ try:
119
+ refused = self._server.sendmail(self._from_addr, [to_addr], msg.as_string())
120
+ except smtplib.SMTPException as exc:
121
+ raise ConnectionFailure(str(exc)) from exc
122
+ if refused:
123
+ code, reason = next(iter(refused.values()))
124
+ raise ConnectionFailure(f"{code} {reason.decode(errors='replace') if isinstance(reason, bytes) else reason}")
125
+ sent_copy = getattr(self, "_sent_copy", None)
126
+ if sent_copy is not None:
127
+ sent_copy.save(msg.as_bytes())
128
+ return msg["Message-ID"]
129
+
130
+ def close(self) -> None:
131
+ try:
132
+ self._server.quit()
133
+ except smtplib.SMTPException:
134
+ pass
135
+ sent_copy = getattr(self, "_sent_copy", None)
136
+ if sent_copy is not None:
137
+ sent_copy.close()
138
+
139
+
140
+ # Providers whose SMTP servers already file a copy of every message in Sent. Adding our own
141
+ # copy there would show each email twice.
142
+ _FILES_SENT_ITSELF = ("smtp.gmail.com", "smtp.googlemail.com", "smtp.office365.com", "smtp-mail.outlook.com")
143
+ _SENT_NAMES = ("Sent", "INBOX.Sent", "Sent Items", "Sent Messages", "INBOX.Sent Items", "Sent Mail")
144
+ _LIST_LINE = re.compile(r'\((?P<flags>[^)]*)\) (?P<sep>"[^"]*"|NIL) (?P<name>.+)')
145
+
146
+
147
+ class SentCopy:
148
+ """Files a copy of each sent message in the mailbox's Sent folder over IMAP, so it shows in
149
+ the person's own webmail (Roundcube and the like) the way mail they send by hand does.
150
+
151
+ Best effort only: the email has already gone by the time this runs, so a missing IMAP
152
+ server, an unknown folder or a timeout is logged and the rest of the campaign carries on.
153
+ One IMAP connection is opened on the first message and reused for the whole campaign."""
154
+
155
+ def __init__(self, smtp_host: str, username: str, password: str, imap: dict | None = None):
156
+ self._username, self._password = username, password
157
+ self._port = 993
158
+ host = smtp_host.strip().lower()
159
+ if imap:
160
+ # The incoming server the person gave us, with its own sign-in and port.
161
+ self._hosts = [imap["host"]]
162
+ self._username, self._password, self._port = imap["username"], imap["password"], imap["port"]
163
+ elif host in _FILES_SENT_ITSELF:
164
+ self._hosts: list[str] = []
165
+ else:
166
+ self._hosts = [f"imap.{host[5:]}", host] if host.startswith("smtp.") else [host]
167
+ self._imap: imaplib.IMAP4_SSL | None = None
168
+ self._folder: str | None = None
169
+ self._given_up = not self._hosts
170
+
171
+ def _connect(self) -> None:
172
+ for host in self._hosts:
173
+ try:
174
+ imap = imaplib.IMAP4_SSL(host, self._port, ssl_context=ssl.create_default_context(), timeout=10)
175
+ imap.login(self._username, self._password)
176
+ except (imaplib.IMAP4.error, OSError) as exc:
177
+ log.info("No IMAP for a Sent copy at %s: %r", host, exc)
178
+ continue
179
+ folder = _sent_folder(imap)
180
+ if folder:
181
+ self._imap, self._folder = imap, folder
182
+ return
183
+ try:
184
+ imap.logout()
185
+ except (imaplib.IMAP4.error, OSError):
186
+ pass
187
+ self._given_up = True
188
+
189
+ def save(self, raw: bytes) -> None:
190
+ if self._given_up:
191
+ return
192
+ try:
193
+ if self._imap is None:
194
+ self._connect()
195
+ if self._imap is None:
196
+ return
197
+ self._imap.append(_quote(self._folder), "\\Seen", imaplib.Time2Internaldate(time.time()), raw)
198
+ except (imaplib.IMAP4.error, OSError) as exc:
199
+ log.warning("Could not file a Sent copy: %r", exc)
200
+ self._given_up = True
201
+
202
+ def close(self) -> None:
203
+ if self._imap is not None:
204
+ try:
205
+ self._imap.logout()
206
+ except (imaplib.IMAP4.error, OSError):
207
+ pass
208
+ self._imap = None
209
+
210
+
211
+ def _quote(name: str) -> str:
212
+ return name if name.startswith('"') else '"' + name.replace("\\", "\\\\").replace('"', '\\"') + '"'
213
+
214
+
215
+ def _sent_folder(imap: imaplib.IMAP4) -> str | None:
216
+ """The folder the server marks as Sent (RFC 6154), else the first common Sent name."""
217
+ status, lines = imap.list()
218
+ if status != "OK":
219
+ return None
220
+ names = []
221
+ for line in lines or []:
222
+ text = line.decode(errors="replace") if isinstance(line, bytes) else str(line)
223
+ m = _LIST_LINE.match(text)
224
+ if not m:
225
+ continue
226
+ name = m.group("name").strip()
227
+ if "\\sent" in m.group("flags").lower():
228
+ return name
229
+ names.append(name.strip('"'))
230
+ for wanted in _SENT_NAMES:
231
+ for name in names:
232
+ if name.lower() == wanted.lower():
233
+ return name
234
+ return None
235
+
236
+
237
+ def build_message(body: str, attachments: list[Attachment], inline_images: list[InlineImage]):
238
+ """An HTML message with a plain-text copy beside it (multipart/alternative), wrapped in
239
+ multipart/related when it carries inline images and in multipart/mixed when it carries
240
+ attachments. Mail that is HTML only is treated as more likely to be spam."""
241
+ content = MIMEText(body, "html", "utf-8")
242
+ if inline_images:
243
+ related = MIMEMultipart("related")
244
+ related.attach(content)
245
+ for img in inline_images:
246
+ part = MIMEImage(img.data, _subtype=img.subtype)
247
+ part.add_header("Content-ID", f"<{img.cid}>")
248
+ part.add_header("Content-Disposition", "inline", filename=f"{img.cid.split('@')[0]}.{img.subtype}")
249
+ related.attach(part)
250
+ content = related
251
+ alternative = MIMEMultipart("alternative")
252
+ alternative.attach(MIMEText(plain_text(body), "plain", "utf-8"))
253
+ alternative.attach(content)
254
+ content = alternative
255
+ if not attachments:
256
+ return content
257
+ mixed = MIMEMultipart("mixed")
258
+ mixed.attach(content)
259
+ for att in attachments:
260
+ maintype, _, subtype = att.content_type.partition("/")
261
+ part = MIMEBase(maintype or "application", subtype or "octet-stream")
262
+ part.set_payload(att.data)
263
+ encoders.encode_base64(part)
264
+ part.add_header("Content-Disposition", "attachment", filename=att.filename)
265
+ mixed.attach(part)
266
+ return mixed
267
+
268
+
269
+
270
+ _BLOCK_END = re.compile(r"</(p|div|h[1-6]|li|tr|table|blockquote|section)\s*>|<br\s*/?>", re.I)
271
+ _LINK = re.compile(r"<a\b[^>]*href=[\"']([^\"']+)[\"'][^>]*>(.*?)</a>", re.I | re.S)
272
+
273
+
274
+ def plain_text(body: str) -> str:
275
+ """A readable text version of an HTML email: one line per block, links as "text (url)"."""
276
+ text = re.sub(r"<(style|script|head)\b.*?</\1>", "", body, flags=re.I | re.S)
277
+ text = re.sub(r"<!--.*?-->", "", text, flags=re.S)
278
+
279
+ def link(m: re.Match) -> str:
280
+ label = re.sub(r"<[^>]+>", "", m.group(2)).strip()
281
+ url = html.unescape(m.group(1))
282
+ if url.startswith(("mailto:", "#")) or not label or label == url:
283
+ return label or url
284
+ return f"{label} ({url})"
285
+
286
+ text = _LINK.sub(link, text)
287
+ text = re.sub(r"<li\b[^>]*>", "- ", text, flags=re.I)
288
+ text = _BLOCK_END.sub("\n", text)
289
+ text = html.unescape(re.sub(r"<[^>]+>", "", text))
290
+ lines = [" ".join(line.split()) for line in text.splitlines()]
291
+ return re.sub(r"\n{3,}", "\n\n", "\n".join(lines)).strip() + "\n"
backend/staff.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ M8ion's own staff: the people who run the product, as opposed to the members of a customer's
3
+ organisation. A staff member is known by a verified email address and holds one or more staff
4
+ roles; each role opens one area under /system. The director can open every area.
5
+
6
+ Firestore layout:
7
+ staff/{email} {roles: [...], added_by, added_at} (email lower-cased, "@" and "." kept)
8
+ audit/{id} {at, by, action, target, detail} (what staff did, newest last)
9
+
10
+ The first director comes from the SYSTEM_DIRECTOR_EMAILS environment variable (comma separated),
11
+ so there is always someone who can add the others. Nothing here reads a customer's content.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import os
17
+ import uuid
18
+ from datetime import datetime, timezone
19
+
20
+ from backend import firestore_client as db
21
+
22
+ # key -> (label, what the area is for). Order is the order they are shown in.
23
+ AREAS: dict[str, tuple[str, str]] = {
24
+ "director": ("Director", "Everything, and who works here."),
25
+ "admin": ("Admin", "Every organisation and individual account, and their plans."),
26
+ "verification": ("Verification", "Identity checks: review each detail and approve or reject it with a reason."),
27
+ "support": ("Support", "Help people with their accounts."),
28
+ "it": ("IT", "Health of the service and its connections."),
29
+ "finance": ("Finance", "Plans, limits and what each account is owed or owes."),
30
+ "compliance": ("Compliance", "Audit trail and policy checks."),
31
+ }
32
+ DIRECTOR = "director"
33
+
34
+
35
+ class StaffError(Exception):
36
+ """A staff action that isn't allowed or doesn't make sense."""
37
+
38
+
39
+ def _now() -> str:
40
+ return datetime.now(timezone.utc).isoformat()
41
+
42
+
43
+ def _key(email: str) -> str:
44
+ return (email or "").strip().lower()
45
+
46
+
47
+ def _bootstrap() -> set[str]:
48
+ return {_key(e) for e in os.getenv("SYSTEM_DIRECTOR_EMAILS", "").split(",") if _key(e)}
49
+
50
+
51
+ def roles_of(email: str) -> list[str]:
52
+ email = _key(email)
53
+ if not email:
54
+ return []
55
+ if email in _bootstrap():
56
+ return [DIRECTOR]
57
+ doc = db.get_doc(f"staff/{email}")
58
+ return [r for r in (doc or {}).get("roles", []) if r in AREAS]
59
+
60
+
61
+ def can_open(roles: list[str], area: str) -> bool:
62
+ return DIRECTOR in roles or area in roles
63
+
64
+
65
+ def describe(email: str) -> dict:
66
+ roles = roles_of(email)
67
+ return {
68
+ "email": _key(email),
69
+ "is_staff": bool(roles),
70
+ "roles": roles,
71
+ "areas": [{"key": k, "label": v[0], "about": v[1], "allowed": can_open(roles, k)} for k, v in AREAS.items()],
72
+ }
73
+
74
+
75
+ def require(email: str, area: str) -> list[str]:
76
+ roles = roles_of(email)
77
+ if not can_open(roles, area):
78
+ raise StaffError("You do not have access to this area")
79
+ return roles
80
+
81
+
82
+ def list_staff() -> list[dict]:
83
+ rows = [{"email": p.split("/", 1)[1], "roles": d.get("roles", []), "added_by": d.get("added_by", ""), "added_at": d.get("added_at")}
84
+ for p, d in db.query_prefix("staff/").items()]
85
+ known = {r["email"] for r in rows}
86
+ rows += [{"email": e, "roles": [DIRECTOR], "added_by": "set up by the host", "added_at": None, "fixed": True} for e in sorted(_bootstrap() - known)]
87
+ return sorted(rows, key=lambda r: r["email"])
88
+
89
+
90
+ def set_roles(actor_email: str, target_email: str, roles: list[str]) -> dict:
91
+ require(actor_email, DIRECTOR)
92
+ target = _key(target_email)
93
+ if "@" not in target or " " in target:
94
+ raise StaffError("Enter a full email address")
95
+ unknown = [r for r in roles if r not in AREAS]
96
+ if unknown:
97
+ raise StaffError(f"Unknown role {unknown[0]!r}")
98
+ if target in _bootstrap():
99
+ raise StaffError("This director is set up by the host and cannot be changed here")
100
+ if _key(actor_email) == target:
101
+ raise StaffError("You cannot change your own roles")
102
+ roles = [r for r in AREAS if r in roles]
103
+ if not roles:
104
+ db.delete_doc(f"staff/{target}")
105
+ else:
106
+ db.set_doc(f"staff/{target}", {"roles": roles, "added_by": _key(actor_email), "added_at": _now()})
107
+ log(actor_email, "staff.set_roles", target, ", ".join(roles) or "removed")
108
+ return {"email": target, "roles": roles}
109
+
110
+
111
+ def log(actor_email: str, action: str, target: str, detail: str = "") -> None:
112
+ db.set_doc(f"audit/{uuid.uuid4().hex}", {"at": _now(), "by": _key(actor_email), "action": action, "target": target, "detail": detail[:500]})
113
+
114
+
115
+ def recent_audit(limit: int = 100) -> list[dict]:
116
+ rows = sorted(db.query_prefix("audit/").values(), key=lambda r: r.get("at", ""), reverse=True)
117
+ return rows[:limit]
118
+
119
+
120
+ # --- every account, for the admin, support and finance areas -------------------------------------
121
+
122
+ ALL_PLANS = ("free", "plus", "starter", "growth", "scale")
123
+
124
+
125
+ def list_orgs() -> list[dict]:
126
+ from backend import accounts, identity
127
+ from backend.auth import lookup_user
128
+
129
+ rows = []
130
+ for path, org in db.query_prefix("orgs/").items():
131
+ org_id = path.split("/", 1)[1]
132
+ owner = org.get("owner_uid", "")
133
+ account = accounts.get_account(owner) or {}
134
+ kind = org.get("kind") or "organization"
135
+ default_plan = "free" if kind == accounts.PERSONAL_KIND else accounts.DEFAULT_ORG_PLAN
136
+ rows.append({
137
+ "org_id": org_id,
138
+ "name": org.get("name", ""),
139
+ "kind": kind,
140
+ "plan": account.get("plan", default_plan),
141
+ "owner_email": lookup_user(owner).get("email", "") or owner,
142
+ "members": len(db.query_prefix(f"orgs/{org_id}/members/")),
143
+ "mail_limit": org.get("mail_limit"),
144
+ "identity": identity.status_of(owner),
145
+ })
146
+ return sorted(rows, key=lambda r: r["name"].lower())
147
+
148
+
149
+ def update_org(actor_email: str, org_id: str, plan: str | None, mail_limit: int | None, set_limit: bool) -> dict:
150
+ from backend import accounts
151
+
152
+ require(actor_email, "admin")
153
+ org = db.get_doc(f"orgs/{org_id}")
154
+ if org is None:
155
+ raise StaffError("No such account")
156
+ owner = org.get("owner_uid", "")
157
+ kind = org.get("kind") or "organization"
158
+ if plan is not None:
159
+ allowed = accounts.INDIVIDUAL_PLANS if kind == accounts.PERSONAL_KIND else accounts.ORG_PLANS
160
+ if plan not in allowed:
161
+ raise StaffError(f"{plan!r} is not a plan for this kind of account (use {', '.join(allowed)})")
162
+ account = accounts.get_account(owner) or {"account_type": accounts.INDIVIDUAL if kind == accounts.PERSONAL_KIND else accounts.ORGANIZATION}
163
+ db.set_doc(f"accounts/{owner}", {**account, "plan": plan})
164
+ if set_limit:
165
+ if mail_limit is not None and mail_limit < 0:
166
+ raise StaffError("The mail limit cannot be negative")
167
+ db.update_doc(f"orgs/{org_id}", {"mail_limit": mail_limit})
168
+ log(actor_email, "org.update", org_id, f"plan={plan} mail_limit={mail_limit if set_limit else 'unchanged'}")
169
+ return next(r for r in list_orgs() if r["org_id"] == org_id)
backend/static/m8ion.js ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*! M8ion Collect snippet. Adds sign-up forms to M8ion lists.
2
+ *
3
+ * <script src="https://YOUR-M8ION-HOST/m8ion.js" defer></script>
4
+ * <form data-m8ion-key="pk_...">
5
+ * <input name="Email" type="email" required>
6
+ * <input name="Name">
7
+ * <button>Join</button>
8
+ * </form>
9
+ *
10
+ * Sends only when the visitor presses submit, and only the fields in that form. No cookies,
11
+ * no tracking, no keystroke capture. Password and file inputs are never read.
12
+ */
13
+ (function () {
14
+ "use strict";
15
+
16
+ var script = document.currentScript;
17
+ var base = script && script.src ? new URL(script.src).origin : "";
18
+ var HP = "m8ion-hp-" + Math.random().toString(36).slice(2, 8);
19
+
20
+ var style = document.createElement("style");
21
+ style.textContent = "." + HP + "{position:absolute!important;left:-9999px!important;width:1px;height:1px;overflow:hidden}";
22
+ document.head.appendChild(style);
23
+
24
+ function show(form, text, ok) {
25
+ var note = form.querySelector("[data-m8ion-message]");
26
+ if (!note) {
27
+ note = document.createElement("p");
28
+ note.setAttribute("data-m8ion-message", "");
29
+ note.setAttribute("role", "status");
30
+ form.appendChild(note);
31
+ }
32
+ note.textContent = text;
33
+ note.style.color = ok ? "" : "#b3261e";
34
+ }
35
+
36
+ function collect(form) {
37
+ var out = {};
38
+ var els = form.elements;
39
+ for (var i = 0; i < els.length; i++) {
40
+ var el = els[i];
41
+ if (!el.name || el.disabled || el.classList.contains(HP)) continue;
42
+ var type = (el.type || "").toLowerCase();
43
+ if (type === "password" || type === "file" || type === "submit" || type === "button") continue;
44
+ if ((type === "checkbox" || type === "radio") && !el.checked) continue;
45
+ out[el.name] = type === "checkbox" ? "Yes" : el.value;
46
+ }
47
+ return out;
48
+ }
49
+
50
+ function bind(form) {
51
+ if (form.getAttribute("data-m8ion-bound")) return;
52
+ form.setAttribute("data-m8ion-bound", "1");
53
+ var key = form.getAttribute("data-m8ion-key");
54
+ var shownAt = Date.now();
55
+
56
+ var trap = document.createElement("input");
57
+ trap.type = "text";
58
+ trap.name = "website";
59
+ trap.tabIndex = -1;
60
+ trap.autocomplete = "off";
61
+ trap.setAttribute("aria-hidden", "true");
62
+ trap.className = HP;
63
+ form.appendChild(trap);
64
+
65
+ form.addEventListener("submit", function (event) {
66
+ event.preventDefault();
67
+ var button = form.querySelector("[type=submit],button:not([type])");
68
+ if (button) button.disabled = true;
69
+ var body = JSON.stringify({ fields: collect(form), hp: trap.value, t: Date.now() - shownAt });
70
+ // text/plain keeps this a "simple" cross-site request, so the browser sends no preflight.
71
+ fetch(base + "/collect/" + encodeURIComponent(key), {
72
+ method: "POST",
73
+ headers: { "Content-Type": "text/plain" },
74
+ body: body,
75
+ })
76
+ .then(function (res) {
77
+ return res.json().then(function (data) { return { ok: res.ok, data: data }; });
78
+ })
79
+ .then(function (r) {
80
+ if (r.ok) {
81
+ var done = form.getAttribute("data-m8ion-success") ||
82
+ (r.data.pending ? "Almost done. Check your email to confirm." : "Thanks, you're signed up.");
83
+ show(form, done, true);
84
+ form.reset();
85
+ } else {
86
+ show(form, r.data.detail || "Something went wrong. Please try again.", false);
87
+ if (button) button.disabled = false;
88
+ }
89
+ })
90
+ .catch(function () {
91
+ show(form, "Could not reach the sign-up service. Please try again.", false);
92
+ if (button) button.disabled = false;
93
+ });
94
+ });
95
+ }
96
+
97
+ function init() {
98
+ var forms = document.querySelectorAll("form[data-m8ion-key]");
99
+ for (var i = 0; i < forms.length; i++) bind(forms[i]);
100
+ }
101
+
102
+ if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init);
103
+ else init();
104
+ })();
backend/storage.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Where the raw copy of an uploaded audience file is kept. An upload is never just parsed and
3
+ discarded, so the original file is stored as well.
4
+
5
+ With SUPABASE_URL and SUPABASE_SERVICE_KEY set the file goes to a private Supabase Storage
6
+ bucket (SUPABASE_BUCKET, default "uploads"). Without them it goes to a local folder, which is
7
+ right for development and wrong for a host whose disk is wiped on restart.
8
+ """
9
+ import os
10
+ from pathlib import Path
11
+
12
+ import httpx
13
+
14
+ TIMEOUT_SECONDS = 30
15
+ CONTENT_TYPES = {
16
+ "csv": "text/csv",
17
+ "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
18
+ }
19
+
20
+
21
+ class StorageError(Exception):
22
+ """The file could not be stored. The upload is refused rather than kept only in memory."""
23
+
24
+
25
+ def _remote() -> tuple[str, str, str] | None:
26
+ url = os.getenv("SUPABASE_URL", "").strip().rstrip("/")
27
+ key = os.getenv("SUPABASE_SERVICE_KEY", "").strip()
28
+ if not url or not key:
29
+ return None
30
+ return url, key, os.getenv("SUPABASE_BUCKET", "uploads").strip() or "uploads"
31
+
32
+
33
+ def save_upload(org_id: str, database_id: str, ext: str, data: bytes) -> str:
34
+ """Stores the original file as {org_id}/{database_id}.{ext}; returns where it went."""
35
+ name = f"{org_id}/{database_id}.{ext}"
36
+ remote = _remote()
37
+ if remote is None:
38
+ path = Path(os.getenv("UPLOADS_DIR", "uploads")) / name
39
+ path.parent.mkdir(parents=True, exist_ok=True)
40
+ path.write_bytes(data)
41
+ return str(path)
42
+
43
+ url, key, bucket = remote
44
+ try:
45
+ res = httpx.post(
46
+ f"{url}/storage/v1/object/{bucket}/{name}",
47
+ content=data,
48
+ headers={
49
+ "Authorization": f"Bearer {key}",
50
+ "Content-Type": CONTENT_TYPES.get(ext.lower(), "application/octet-stream"),
51
+ "x-upsert": "true",
52
+ },
53
+ timeout=TIMEOUT_SECONDS,
54
+ )
55
+ except httpx.HTTPError as err:
56
+ raise StorageError(f"Could not reach file storage: {err.__class__.__name__}") from err
57
+ if res.status_code >= 300:
58
+ raise StorageError(f"File storage refused the file ({res.status_code})")
59
+ return f"{bucket}/{name}"
backend/templating.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Per-recipient message rendering: {Field} placeholders, {Field|fallback}, list fields as bullets
3
+ or an inline "A, B and C", and {if Field has "x"}...{else}...{/if} conditional blocks.
4
+
5
+ One engine serves both the real send and the Campaigns page's preview, so what is previewed is
6
+ what is sent. Row values are HTML-escaped when rendering HTML (a value containing "<" must not
7
+ become markup in someone's inbox); the subject is rendered as plain text and is not escaped.
8
+
9
+ A template that cannot be rendered safely (unclosed {if}, stray {else}, a condition that does
10
+ not parse) is reported by validate_template so a send is refused up front instead of going out
11
+ half-rendered to every recipient.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import html as html_lib
17
+ import re
18
+ from dataclasses import dataclass, field
19
+
20
+ LIST_SPLIT_MIXED = re.compile(r"[;,|\n]")
21
+ _BLOCK_TOKEN = re.compile(r"\{(?:if\s+([^{}]*)|(else)|(/if))\}")
22
+ _PLACEHOLDER = re.compile(r"\{([A-Za-z0-9_][A-Za-z0-9_ ]*?)(?:\|([^{}]*))?\}")
23
+ _PARAGRAPH_TOKEN = re.compile(r"<p(?:\s[^>]*)?>\s*(\{(?:if\s[^{}]*|else|/if)\})\s*</p>", re.IGNORECASE)
24
+ _PARAGRAPH_LIST = re.compile(r"<p(?:\s[^>]*)?>\s*\{([A-Za-z0-9_][A-Za-z0-9_ ]*?)(?:\|(bullets|inline))?\}\s*</p>", re.IGNORECASE)
25
+ _CONDITION = re.compile(
26
+ r"""^(?P<field>[A-Za-z0-9_][A-Za-z0-9_ ]*?)\s+
27
+ (?P<op>is\ not\ empty|is\ empty|is\ true|is\ false|does\ not\ contain|is\ not|is|has\ not|lacks|has|contains)
28
+ (?:\s+["“”'](?P<value>.*?)["“”'])?\s*$""",
29
+ re.VERBOSE | re.IGNORECASE,
30
+ )
31
+ _NEEDS_VALUE = {"is", "is not", "has", "has not", "lacks", "contains", "does not contain"}
32
+
33
+ _UL_STYLE = "margin:0 0 14px;padding-left:22px;"
34
+ _LI_STYLE = "margin:0 0 4px;"
35
+
36
+
37
+ class TemplateError(ValueError):
38
+ pass
39
+
40
+
41
+ @dataclass
42
+ class _Cond:
43
+ field: str
44
+ op: str
45
+ value: str
46
+
47
+
48
+ @dataclass
49
+ class _If:
50
+ cond: _Cond
51
+ then: list = field(default_factory=list)
52
+ other: list = field(default_factory=list)
53
+
54
+
55
+ def split_items(text: str, delimiter: str | None) -> list[str]:
56
+ """Splits a list-style cell into trimmed, non-empty items. delimiter "mixed" accepts any of
57
+ ; , | or a newline in the same cell (people are inconsistent), anything else is literal."""
58
+ if not text:
59
+ return []
60
+ if delimiter == "mixed":
61
+ parts = LIST_SPLIT_MIXED.split(text)
62
+ else:
63
+ parts = text.split(delimiter or ";")
64
+ return [p.strip() for p in parts if p.strip()]
65
+
66
+
67
+ def _parse_condition(raw: str) -> _Cond:
68
+ m = _CONDITION.match(html_lib.unescape(raw).strip())
69
+ if not m:
70
+ raise TemplateError(f'Could not read the condition "{{if {raw.strip()}}}"')
71
+ op = re.sub(r"\s+", " ", m.group("op").lower())
72
+ value = m.group("value")
73
+ if op in _NEEDS_VALUE and value is None:
74
+ raise TemplateError(f'The condition "{{if {raw.strip()}}}" needs a value in quotes')
75
+ return _Cond(m.group("field").strip(), op, (value or "").strip())
76
+
77
+
78
+ def _parse(template: str) -> list:
79
+ """Template text -> tree of str and _If nodes. Raises TemplateError on unbalanced blocks."""
80
+ root: list = []
81
+ stack: list[tuple[_If, bool]] = [] # (node, currently_in_else)
82
+ current = root
83
+ pos = 0
84
+ for m in _BLOCK_TOKEN.finditer(template):
85
+ if m.start() > pos:
86
+ current.append(template[pos:m.start()])
87
+ pos = m.end()
88
+ if m.group(1) is not None:
89
+ node = _If(_parse_condition(m.group(1)))
90
+ current.append(node)
91
+ stack.append((node, False))
92
+ current = node.then
93
+ elif m.group(2):
94
+ if not stack or stack[-1][1]:
95
+ raise TemplateError("Found {else} without a matching {if ...}")
96
+ node, _ = stack[-1]
97
+ stack[-1] = (node, True)
98
+ current = node.other
99
+ else:
100
+ if not stack:
101
+ raise TemplateError("Found {/if} without a matching {if ...}")
102
+ stack.pop()
103
+ current = stack[-1][0].other if stack and stack[-1][1] else (stack[-1][0].then if stack else root)
104
+ if stack:
105
+ raise TemplateError("An {if ...} block is missing its {/if}")
106
+ if pos < len(template):
107
+ current.append(template[pos:])
108
+ return root
109
+
110
+
111
+ def _column_defs(columns: list[dict] | None) -> dict[str, dict]:
112
+ return {c["name"]: c for c in (columns or [])}
113
+
114
+
115
+ def _evaluate(cond: _Cond, row: dict, cols: dict[str, dict]) -> bool:
116
+ col = cols.get(cond.field)
117
+ if col is None and cols:
118
+ return False # a condition on a field the audience does not have never matches
119
+ text = str(row.get(cond.field, "") or "")
120
+ col_type = (col or {}).get("type", "text")
121
+ needle = cond.value.strip().lower()
122
+ op = cond.op
123
+
124
+ if op == "is empty":
125
+ return text.strip() == ""
126
+ if op == "is not empty":
127
+ return text.strip() != ""
128
+ if op in ("is true", "is false"):
129
+ truthy = text.strip().lower() in {"true", "yes", "y", "1"}
130
+ return truthy if op == "is true" else not truthy
131
+
132
+ if col_type == "tag":
133
+ items = {i.lower() for i in split_items(text, col.get("delimiter"))}
134
+ if op in ("has", "is"):
135
+ return needle in items
136
+ if op in ("lacks", "has not", "is not"):
137
+ return needle not in items
138
+ hay = text.strip().lower()
139
+ if op == "is":
140
+ return hay == needle
141
+ if op == "is not":
142
+ return hay != needle
143
+ if op in ("has", "lacks", "has not"):
144
+ # On a plain column "has" means the whole word/phrase appears, so "yes" is not
145
+ # matched by "yesterday".
146
+ found = re.search(r"(?<!\w)" + re.escape(needle) + r"(?!\w)", hay) is not None
147
+ return found if op == "has" else not found
148
+ if op == "contains":
149
+ return needle in hay
150
+ if op == "does not contain":
151
+ return needle not in hay
152
+ return False
153
+
154
+
155
+ def _inline_join(items: list[str]) -> str:
156
+ if len(items) <= 1:
157
+ return "".join(items)
158
+ return ", ".join(items[:-1]) + " and " + items[-1]
159
+
160
+
161
+ def _bullets(items: list[str], escape: bool) -> str:
162
+ esc = html_lib.escape if escape else (lambda s: s)
163
+ lis = "".join(f'<li style="{_LI_STYLE}">{esc(i)}</li>' for i in items)
164
+ return f'<ul style="{_UL_STYLE}">{lis}</ul>'
165
+
166
+
167
+ def _render_text(text: str, row: dict, cols: dict[str, dict], html: bool) -> str:
168
+ esc = html_lib.escape if html else (lambda s: s)
169
+
170
+ if html:
171
+ # A list field alone in its paragraph becomes a real bullet list (replacing the paragraph).
172
+ def paragraph_list(m: re.Match) -> str:
173
+ name, mode = m.group(1).strip(), (m.group(2) or "").lower()
174
+ col = cols.get(name)
175
+ if not col or col.get("type") != "tag" or mode == "inline":
176
+ return m.group(0)
177
+ items = split_items(str(row.get(name, "") or ""), col.get("delimiter"))
178
+ return _bullets(items, True) if items else ""
179
+
180
+ text = _PARAGRAPH_LIST.sub(paragraph_list, text)
181
+
182
+ def placeholder(m: re.Match) -> str:
183
+ name, option = m.group(1).strip(), m.group(2)
184
+ col = cols.get(name)
185
+ raw = str(row.get(name, "") or "")
186
+ if col and col.get("type") == "tag":
187
+ items = split_items(raw, col.get("delimiter"))
188
+ if items:
189
+ if option and option.lower() == "bullets" and html:
190
+ return _bullets(items, True)
191
+ return esc(_inline_join(items))
192
+ elif raw.strip():
193
+ return esc(raw)
194
+ if option and option.lower() not in ("bullets", "inline"):
195
+ return option # fallback text written by the author
196
+ return ""
197
+
198
+ return _PLACEHOLDER.sub(placeholder, text)
199
+
200
+
201
+ def _render(nodes: list, row: dict, cols: dict[str, dict], html: bool) -> str:
202
+ out = []
203
+ for node in nodes:
204
+ if isinstance(node, str):
205
+ out.append(_render_text(node, row, cols, html))
206
+ else:
207
+ branch = node.then if _evaluate(node.cond, row, cols) else node.other
208
+ out.append(_render(branch, row, cols, html))
209
+ return "".join(out)
210
+
211
+
212
+ def _prepare(template: str) -> str:
213
+ # {if}/{else}/{/if} typed on their own line become their own <p>; drop that wrapper so the
214
+ # block leaves no empty paragraphs behind.
215
+ return _PARAGRAPH_TOKEN.sub(r"\1", template)
216
+
217
+
218
+ def validate_template(template: str, columns: list[dict] | None = None) -> list[str]:
219
+ """Problems that would make the template render wrongly. Empty list means safe to send."""
220
+ problems: list[str] = []
221
+ try:
222
+ tree = _parse(_prepare(template))
223
+ except TemplateError as exc:
224
+ return [str(exc)]
225
+ names = {c["name"] for c in (columns or [])}
226
+ if names:
227
+ def walk(nodes: list) -> None:
228
+ for n in nodes:
229
+ if isinstance(n, _If):
230
+ if n.cond.field not in names:
231
+ problems.append(f'A condition uses the field "{n.cond.field}", which this audience does not have')
232
+ walk(n.then)
233
+ walk(n.other)
234
+ walk(tree)
235
+ return list(dict.fromkeys(problems))
236
+
237
+
238
+ def render(template: str, row: dict, columns: list[dict] | None = None, html: bool = True) -> str:
239
+ """Renders one recipient's copy. Raises TemplateError if the template is malformed."""
240
+ tree = _parse(_prepare(template) if html else template)
241
+ return _render(tree, row, _column_defs(columns), html)