Spaces:
Running
Running
Download backend/collect.py from Success-dev/receipter-pro: direct link, hf CLI and curl.
- Browser
- Download file 15.3 kB
-
https://huggingface.co/spaces/Success-dev/receipter-pro/resolve/main/backend/collect.py
- Command line
-
hf download hf://spaces/Success-dev/receipter-pro/backend/collect.py
-
curl -L -o collect.py https://huggingface.co/spaces/Success-dev/receipter-pro/resolve/main/backend/collect.py
15.3 kB
| """ | |
| Public collection ("Collect") — lets people on a user's own website land in one of that user's | |
| databases through a public key + a snippet. See docs/blueprint/adr/0006. | |
| The public key is NOT a secret and can do almost nothing: create a *pending* sign-up. Its rules | |
| live here, server-side (allowed origins, allowed columns, daily cap, double opt-in). A sign-up | |
| only becomes a database row once the person confirms from their inbox, and every check that | |
| could stop a bot runs BEFORE a confirmation email is sent — that email goes out from the user's | |
| own mailbox, so one sent to a stranger costs the user's sender reputation. | |
| This module is the only thing the public router (backend/collect_api.py) may call. It never | |
| reads rows out, never exposes credentials, and never sends a campaign. | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import html | |
| import json | |
| import logging | |
| import os | |
| import secrets | |
| import uuid | |
| from datetime import datetime, timedelta, timezone | |
| from backend import databases, mailboxes, mailer_client, orgs, rate_limiter, workbook | |
| from backend import firestore_client as db | |
| from backend.core import constants as C | |
| from backend.crypto_utils import decrypt, encrypt | |
| from backend.mock_mailer import AuthError, ConnectionFailure | |
| class CollectError(Exception): | |
| """A hard rejection the public caller is allowed to see. `status` is the HTTP code.""" | |
| def __init__(self, status: int, message: str): | |
| self.status = status | |
| super().__init__(message) | |
| def _now() -> datetime: | |
| return datetime.now(timezone.utc) | |
| def _key_path(org_id: str, key_id: str) -> str: | |
| return f"orgs/{org_id}/collect_keys/{key_id}" | |
| def _index_path(public_key: str) -> str: | |
| return f"collect_index/{public_key}" | |
| def _pending_path(token: str) -> str: | |
| return f"collect_pending/{token}" | |
| def _consent_path(org_id: str, row_id: str) -> str: | |
| return f"orgs/{org_id}/consents/{row_id}" | |
| def _blocked(field: str) -> bool: | |
| lowered = field.lower() | |
| return any(word in lowered for word in C.COLLECT_BLOCKED_FIELD_WORDS) | |
| def _normalize_origin(origin: str) -> str: | |
| origin = origin.strip().rstrip("/").lower() | |
| if not (origin.startswith("http://") or origin.startswith("https://")) or "/" in origin.split("://", 1)[1]: | |
| raise ValueError(f"{origin!r} is not a site address. Use something like https://example.com") | |
| return origin | |
| def _email_column(database: dict) -> str | None: | |
| for col in database["columns"]: | |
| if col["type"] == "email": | |
| return col["name"] | |
| return None | |
| # --- Key management (signed-in users) --------------------------------------- | |
| def _clean_welcome(org_id: str, welcome: dict | None, default_mailbox: str | None) -> dict | None: | |
| """A welcome email: {subject, html_body, mailbox_connection_id}, or None for no welcome.""" | |
| if not welcome or not (welcome.get("subject") or welcome.get("html_body")): | |
| return None | |
| subject, body = str(welcome.get("subject", "")).strip(), str(welcome.get("html_body", "")).strip() | |
| if not subject or not body: | |
| raise ValueError("A welcome email needs both a subject and a message") | |
| mailbox_id = welcome.get("mailbox_connection_id") or default_mailbox | |
| if not mailbox_id: | |
| raise ValueError("Pick a mailbox to send the welcome email from") | |
| if mailboxes.get_mailbox(org_id, mailbox_id)["status"] != "verified": | |
| raise ValueError("That mailbox is not verified yet, so it cannot send the welcome email.") | |
| return {"subject": subject, "html_body": body, "mailbox_connection_id": mailbox_id} | |
| def set_welcome(org_id: str, actor_uid: str, key_id: str, welcome: dict | None) -> dict | None: | |
| orgs.require_permission(org_id, actor_uid, "edit_lists") | |
| doc = db.get_doc(_key_path(org_id, key_id)) | |
| if doc is None: | |
| raise orgs.NotFoundError(f"No form {key_id!r}") | |
| cleaned = _clean_welcome(org_id, welcome, doc.get("mailbox_connection_id")) | |
| db.update_doc(_key_path(org_id, key_id), {"welcome": cleaned}) | |
| return cleaned | |
| def _send_welcome(org_id: str, key: dict, row_id: str) -> None: | |
| """Queues the form's welcome email to the one person who just joined. A failure here never | |
| turns away the sign-up; the person is on the list either way.""" | |
| welcome = key.get("welcome") | |
| if not welcome: | |
| return | |
| from backend import sending # late: sending pulls in much of the app | |
| try: | |
| sending.queue_campaign( | |
| org_id, key.get("created_by", ""), welcome["subject"], welcome["html_body"], welcome["mailbox_connection_id"], | |
| key["database_id"], only_row_ids=[row_id], automated=True, | |
| ) | |
| except Exception: # noqa: BLE001 - see docstring | |
| logging.getLogger(__name__).exception("Welcome email for form %s could not be queued", key.get("name")) | |
| def create_key( | |
| org_id: str, actor_uid: str, name: str, database_id: str, allowed_origins: list[str], | |
| fields: list[str] | None = None, double_opt_in: bool = True, | |
| mailbox_connection_id: str | None = None, daily_cap: int = C.COLLECT_DEFAULT_DAILY_CAP, | |
| welcome: dict | None = None, | |
| ) -> dict: | |
| orgs.require_permission(org_id, actor_uid, "edit_lists") | |
| name = name.strip() | |
| if not name or len(name) > 80: | |
| raise ValueError("Give the form a name (up to 80 characters)") | |
| database = databases.get_database(org_id, database_id) | |
| email_column = _email_column(database) | |
| if email_column is None: | |
| raise ValueError("This list has no email column yet, so people cannot sign up to it. Set one first.") | |
| column_names = [c["name"] for c in database["columns"]] | |
| chosen = column_names if not fields else fields | |
| unknown = [f for f in chosen if f not in column_names] | |
| if unknown: | |
| raise ValueError(f"Not a column in this list: {', '.join(unknown)}") | |
| chosen = [f for f in chosen if not _blocked(f)] | |
| if email_column not in chosen: | |
| chosen.insert(0, email_column) | |
| if double_opt_in: | |
| if not mailbox_connection_id: | |
| raise ValueError("Pick a mailbox to send the confirmation email from, or turn confirmation off.") | |
| if mailboxes.get_mailbox(org_id, mailbox_connection_id)["status"] != "verified": | |
| raise ValueError("That mailbox is not verified yet, so it cannot send confirmation emails.") | |
| if not 1 <= daily_cap <= 10_000: | |
| raise ValueError("Daily limit must be between 1 and 10,000") | |
| origins = list(dict.fromkeys(_normalize_origin(o) for o in allowed_origins if o.strip())) | |
| key_id = uuid.uuid4().hex | |
| public_key = "pk_" + secrets.token_urlsafe(18) | |
| doc = { | |
| "name": name, | |
| "database_id": database_id, | |
| "public_key": public_key, | |
| "allowed_origins": origins, | |
| "fields": chosen, | |
| "double_opt_in": double_opt_in, | |
| "mailbox_connection_id": mailbox_connection_id if double_opt_in else None, | |
| "daily_cap": daily_cap, | |
| "welcome": _clean_welcome(org_id, welcome, mailbox_connection_id), | |
| "created_by": actor_uid, | |
| "revoked": False, | |
| "created_at": _now().isoformat(), | |
| } | |
| db.set_doc(_key_path(org_id, key_id), doc) | |
| db.set_doc(_index_path(public_key), {"org_id": org_id, "key_id": key_id}) | |
| return doc | {"key_id": key_id} | |
| def list_keys(org_id: str, actor_uid: str) -> list[dict]: | |
| orgs.require_permission(org_id, actor_uid) | |
| prefix = f"orgs/{org_id}/collect_keys/" | |
| items = [data | {"key_id": path[len(prefix):]} for path, data in db.query_prefix(prefix).items()] | |
| return sorted(items, key=lambda k: k["created_at"], reverse=True) | |
| def revoke_key(org_id: str, actor_uid: str, key_id: str) -> None: | |
| orgs.require_permission(org_id, actor_uid, "edit_lists") | |
| doc = db.get_doc(_key_path(org_id, key_id)) | |
| if doc is None: | |
| raise orgs.NotFoundError(f"No form {key_id!r}") | |
| db.update_doc(_key_path(org_id, key_id), {"revoked": True}) | |
| db.delete_doc(_index_path(doc["public_key"])) | |
| # --- Public side --------------------------------------------------------------- | |
| def _load_key(public_key: str) -> tuple[str, str, dict]: | |
| index = db.get_doc(_index_path(public_key)) | |
| if index is None: | |
| raise CollectError(404, "Unknown form") | |
| doc = db.get_doc(_key_path(index["org_id"], index["key_id"])) | |
| if doc is None or doc["revoked"]: | |
| raise CollectError(404, "Unknown form") | |
| return index["org_id"], index["key_id"], doc | |
| def allowed_origin(public_key: str, origin: str | None) -> str | None: | |
| """The value for Access-Control-Allow-Origin for this key and caller, or None.""" | |
| try: | |
| _, _, key = _load_key(public_key) | |
| except CollectError: | |
| return None | |
| if not origin: | |
| return None | |
| origin = origin.strip().rstrip("/").lower() | |
| if not key["allowed_origins"] or origin in key["allowed_origins"]: | |
| return origin | |
| return None | |
| def submit(public_key: str, payload: object, origin: str | None, client_ip: str) -> dict: | |
| """Handles one public sign-up. Returns {"ok": True, "pending": bool}. Raises CollectError | |
| only for things a real visitor or the site owner needs to know about; bots caught by the | |
| cheap checks get a normal-looking success so they learn nothing.""" | |
| org_id, key_id, key = _load_key(public_key) | |
| pending_mode = key["double_opt_in"] | |
| ok = {"ok": True, "pending": pending_mode} | |
| if key["allowed_origins"] and (not origin or origin.strip().rstrip("/").lower() not in key["allowed_origins"]): | |
| raise CollectError(403, "This form is not allowed on this site") | |
| if not isinstance(payload, dict) or not isinstance(payload.get("fields"), dict): | |
| raise CollectError(400, "Malformed submission") | |
| raw_fields = payload["fields"] | |
| if len(raw_fields) > C.COLLECT_MAX_FIELDS or len(json.dumps(payload)) > C.COLLECT_MAX_BODY_BYTES: | |
| raise CollectError(413, "Submission is too large") | |
| # Cheap bot checks: honeypot filled, or filled in faster than a person can. | |
| if payload.get("hp"): | |
| return ok | |
| elapsed = payload.get("t") | |
| if isinstance(elapsed, (int, float)) and elapsed < C.COLLECT_MIN_FILL_SECONDS * 1000: | |
| return ok | |
| if not rate_limiter.allow_hit(f"collect-key:{key_id}", C.COLLECT_PER_KEY_PER_MINUTE, 60): | |
| raise CollectError(429, "Too many sign-ups right now. Try again in a minute.") | |
| ip_hash = hashlib.sha256(client_ip.encode()).hexdigest()[:16] | |
| if not rate_limiter.allow_hit(f"collect-ip:{ip_hash}", C.COLLECT_PER_IP_PER_MINUTE, 60): | |
| raise CollectError(429, "Too many sign-ups from your connection. Try again in a minute.") | |
| database = databases.get_database(org_id, key["database_id"]) | |
| email_column = _email_column(database) | |
| if email_column is None: | |
| raise CollectError(409, "This form is not set up correctly") | |
| values = {} | |
| for name, value in raw_fields.items(): | |
| if name not in key["fields"] or _blocked(name) or isinstance(value, (dict, list)): | |
| continue | |
| text = str(value).strip()[: C.COLLECT_MAX_VALUE_LENGTH] | |
| if text: | |
| values[name] = text | |
| email = values.get(email_column, "") | |
| if not databases.EMAIL_RE.match(email): | |
| raise CollectError(400, "Please enter a valid email address") | |
| if not rate_limiter.allow_hit(f"collect-day:{key_id}", key["daily_cap"], 86_400): | |
| raise CollectError(429, "This form has reached its daily limit") | |
| digest = hashlib.sha256(email.lower().encode()).hexdigest()[:20] | |
| if not rate_limiter.allow_hit(f"collect-addr:{key_id}:{digest}", C.COLLECT_PER_ADDRESS_PER_HOUR, 3600): | |
| return ok # already asked recently; do not email them again, do not say so | |
| # Someone who fills the form in again gets a new row, so nothing they gave before is lost. | |
| # Sends use their newest entry; different answers are flagged on the audiences page. | |
| if not pending_mode: | |
| row_id = databases.insert_row(org_id, key["database_id"], values) | |
| workbook.mark_stale(org_id) | |
| _record_consent(org_id, row_id, key_id, email) | |
| _send_welcome(org_id, key, row_id) | |
| return ok | |
| token = secrets.token_urlsafe(24) | |
| expires = _now() + timedelta(hours=C.COLLECT_CONFIRM_TTL_HOURS) | |
| db.set_doc(_pending_path(token), { | |
| "org_id": org_id, | |
| "key_id": key_id, | |
| "database_id": key["database_id"], | |
| "encrypted_values": encrypt(json.dumps(values)), | |
| "expires_at": expires.isoformat(), | |
| }) | |
| try: | |
| _send_confirmation(org_id, key, email, token) | |
| except CollectError: | |
| db.delete_doc(_pending_path(token)) | |
| raise | |
| return ok | |
| def _send_confirmation(org_id: str, key: dict, email: str, token: str) -> None: | |
| try: | |
| rate_limiter.check_and_consume(org_id, count=1) | |
| except rate_limiter.RateLimitExceeded as exc: | |
| raise CollectError(429, "Confirmation emails are paused for now. Try again later.") from exc | |
| connection = mailboxes.get_mailbox(org_id, key["mailbox_connection_id"]) | |
| if connection["status"] != "verified": | |
| raise CollectError(503, "This form cannot send confirmation emails right now") | |
| org_name = html.escape(orgs.get_org(org_id)["name"]) | |
| base = os.getenv("PUBLIC_API_BASE_URL", "http://localhost:8000").rstrip("/") | |
| link = f"{base}/collect/confirm/{token}" | |
| body = ( | |
| f"<p>Please confirm your email address to join {org_name}'s list.</p>" | |
| f'<p><a href="{html.escape(link)}">Yes, add me</a></p>' | |
| f"<p>If you did not ask for this, ignore this email and nothing will happen.</p>" | |
| ) | |
| mailer = mailer_client.get_mailer(connection["kind"], mailboxes.get_decrypted_credentials(org_id, key["mailbox_connection_id"])) | |
| try: | |
| mailer.send(to_addr=email, subject=f"Confirm your email for {orgs.get_org(org_id)['name']}", body=body) | |
| except (AuthError, ConnectionFailure) as exc: | |
| raise CollectError(503, "Could not send the confirmation email. Try again later.") from exc | |
| def _record_consent(org_id: str, row_id: str, key_id: str, email: str) -> None: | |
| db.set_doc(_consent_path(org_id, row_id), { | |
| "key_id": key_id, | |
| "email_hash": hashlib.sha256(email.lower().encode()).hexdigest(), | |
| "confirmed_at": _now().isoformat(), | |
| }) | |
| def confirm(token: str) -> str: | |
| """Turns a pending sign-up into a row. Returns "confirmed", "expired" or "invalid".""" | |
| pending = db.get_doc(_pending_path(token)) | |
| if pending is None: | |
| return "invalid" | |
| if datetime.fromisoformat(pending["expires_at"]) < _now(): | |
| db.delete_doc(_pending_path(token)) | |
| return "expired" | |
| values = json.loads(decrypt(pending["encrypted_values"])) | |
| org_id = pending["org_id"] | |
| db.delete_doc(_pending_path(token)) # single use, even if the insert below fails | |
| try: | |
| row_id = databases.insert_row(org_id, pending["database_id"], values) | |
| except orgs.NotFoundError: | |
| return "invalid" # the list was deleted since | |
| workbook.mark_stale(org_id) | |
| email_column = _email_column(databases.get_database(org_id, pending["database_id"])) | |
| _record_consent(org_id, row_id, pending["key_id"], values.get(email_column or "", "")) | |
| key = db.get_doc(_key_path(org_id, pending["key_id"])) | |
| if key: | |
| _send_welcome(org_id, key, row_id) | |
| return "confirmed" | |