Spaces:
Sleeping

curium-intel / feedback_form.py
Piers Lyon
Claude Opus 4.7 (1M context)
Harden public feedback form against abuse + roster leak
bd531ac
Raw History Blame Contribute Delete
9.94 kB
"""
Public feedback form (feedback_form.py)
Renders an unauth Streamlit page accessed via `?form=feedback` in the
URL. Linked from the bottom of every weekly digest email so recipients
can submit feedback without dealing with email reply-routing or the
Application Access Policy gymnastics required for the Graph mailbox
poll path.
What it captures:
- Recipient name (pre-filled from `?from=` query param when present)
- Free-form feedback text
On submit:
- Inserts a feedback_messages row with a synthetic message_id
(web-form-<utc-iso>-<colleague>) so it's distinguishable from
mailbox-poll messages but flows through the same downstream
feedback_digest summariser.
- Calls feedback_ingest.parse_reply_to_signals() to LLM-parse the
body into feedback_signals.
- Shows a tight thank-you screen.
Light touch on UX β€” the form is something a busy partner will fill in
on their phone, so: one input, big textarea, one button, done.
"""
from __future__ import annotations
import os
import hmac
import hashlib
import sqlite3
import time
from datetime import datetime
from pathlib import Path
import streamlit as st
import yaml
DATABASE = "leads.db"
CONFIG_PATH = Path(__file__).parent / "config.yaml"
# Security knobs
MAX_BODY_CHARS = 4000 # truncated at the DB layer; this is the input cap
MIN_BODY_CHARS = 8 # rejects "hi" / single-word submissions
SESSION_SUBMISSION_LIMIT = 5 # hard cap per Streamlit session
SUBMISSION_COOLDOWN_SECS = 20 # min seconds between submits in one session
def _signing_key() -> bytes:
"""Shared secret used to HMAC-sign the recipient name in digest URLs.
Falls back to a deterministic per-deployment value derived from
other secrets so the form keeps working if FEEDBACK_SIGNING_KEY
hasn't been set explicitly β€” but ADMINS should set it explicitly
for production-grade integrity.
"""
explicit = os.environ.get("FEEDBACK_SIGNING_KEY")
if explicit:
return explicit.encode("utf-8")
# Fallback: derive a stable key from other secrets so URLs in
# already-sent emails don't break across deploys. Not as strong
# as a dedicated secret but better than no signing.
parts = [
os.environ.get("ANTHROPIC_API_KEY", ""),
os.environ.get("MS_GRAPH_TENANT_ID", ""),
os.environ.get("HF_STATE_REPO", ""),
]
seed = "|".join(p for p in parts if p) or "curium-feedback-default-seed"
return hashlib.sha256(seed.encode("utf-8")).digest()
def sign_recipient(name: str) -> str:
"""Return a short URL-safe HMAC tag for the given recipient name.
Used by weekly_digest._feedback_prompt_html when building the
per-recipient form URL."""
if not name:
return ""
mac = hmac.new(_signing_key(), name.encode("utf-8"), hashlib.sha256).hexdigest()
return mac[:16] # 16 hex chars = 64 bits, enough to deter forgery
def _verify_signature(name: str, tag: str) -> bool:
if not name or not tag:
return False
try:
return hmac.compare_digest(sign_recipient(name), tag)
except Exception:
return False
def _is_known_colleague(name: str) -> bool:
"""Is `name` in the enabled team_emails list? Names are NOT exposed
to the form's UI β€” used only to validate signed query params."""
try:
cfg = yaml.safe_load(CONFIG_PATH.read_text())
names = {
(entry.get("name") or "").strip().lower()
for entry in (cfg.get("team_emails") or [])
if entry.get("name") and entry.get("enabled", True)
}
return (name or "").strip().lower() in names
except Exception:
return False
def _check_rate_limit() -> tuple[bool, str]:
"""Per-session abuse guard. Combines a hard count limit + cooldown
between submissions. Streamlit session state survives across reruns
in the same browser tab; clearing cookies resets it (acceptable β€”
this is anti-noise, not anti-state-actor)."""
submits = st.session_state.get("_fb_submits", [])
now = time.time()
submits = [t for t in submits if now - t < 600] # keep last 10 min
if len(submits) >= SESSION_SUBMISSION_LIMIT:
return False, "Submission limit reached for this session. Try again later."
if submits and (now - submits[-1]) < SUBMISSION_COOLDOWN_SECS:
wait = int(SUBMISSION_COOLDOWN_SECS - (now - submits[-1]))
return False, f"Hold on {wait}s before sending another one."
return True, ""
def _record_submission() -> None:
submits = st.session_state.get("_fb_submits", [])
submits.append(time.time())
st.session_state["_fb_submits"] = submits
def _submit(colleague: str, body: str) -> tuple[bool, str]:
"""Persist a web-form submission and parse it into structured
feedback_signals. Returns (ok, message-shown-to-user)."""
body = (body or "").strip()
if not body:
return False, "Add a sentence or two of feedback first."
if len(body) < MIN_BODY_CHARS:
return False, "Too short β€” give us a bit more to work with."
if len(body) > MAX_BODY_CHARS:
# Hard truncate at the input layer so a very long paste doesn't
# inflate LLM cost.
body = body[:MAX_BODY_CHARS]
ok, msg = _check_rate_limit()
if not ok:
return False, msg
# Ensure schema exists (idempotent β€” safe on Spaces cold start)
try:
from collator import init_company_db
init_company_db()
except Exception:
pass
now = datetime.utcnow().isoformat()
safe_slug = "".join(c for c in (colleague or "anon").lower() if c.isalnum() or c == "-") or "anon"
msg_id = f"web-form-{now}-{safe_slug}"
# Parse via the same LLM path used for mailbox replies
try:
from feedback_ingest import parse_reply_to_signals, _store_message
except ImportError as e:
return False, f"Internal error β€” couldn't load parser: {e}"
signals = parse_reply_to_signals(body, progress_cb=lambda m: None)
fake_msg = {
"message_id": msg_id,
"sender": f"{safe_slug}@web-form.curium",
"sender_name": colleague or "Anonymous",
"subject": "Curium digest feedback (web form)",
"body_text": body,
"received_at": now,
}
_store_message(fake_msg, signals,
recipient_override=colleague if colleague else None)
_record_submission()
return True, (
f"Thanks{', ' + colleague if colleague else ''}. "
f"{len(signals)} signal{'s' if len(signals) != 1 else ''} captured β€” "
f"you'll see what we did with it at the top of next Monday's digest."
)
def render_feedback_form() -> None:
"""Render the form. Called from app.py when ?form=feedback is set."""
st.set_page_config(
page_title="Curium digest feedback",
page_icon="πŸ’¬",
layout="centered",
initial_sidebar_state="collapsed",
)
# Hide the default Streamlit chrome β€” the form should feel like a
# standalone page, not "an app".
st.markdown(
"""
<style>
#MainMenu, footer, header { visibility: hidden; }
.block-container { padding-top: 2rem; max-width: 640px; }
</style>
""",
unsafe_allow_html=True,
)
st.markdown(
'<div style="text-align:center;margin-bottom:24px;">'
'<span style="font-size:1.6em;font-weight:800;color:#1a237e;">CURIUM</span>'
'<div style="color:#78909c;font-size:0.95em;">Digest feedback</div>'
'</div>',
unsafe_allow_html=True,
)
st.markdown(
'<p style="color:#37474f;">'
'Tell us what worked, what didn\'t, what you want more or less of. '
'Anything from one line to a paragraph. We read every submission '
'and surface what you said at the top of next Monday\'s digest.</p>',
unsafe_allow_html=True,
)
# Pre-fill the recipient name ONLY from a SIGNED query param. The
# email footer builds links like `?from=Stu&sig=<hmac>`; without a
# valid signature we never expose internal team names, and the user
# has to type their own name in a free-text box. This stops a
# forwarded URL from letting outsiders pose as a team member or
# enumerate the team roster.
qp_from = (st.query_params.get("from") or "").strip()
qp_sig = (st.query_params.get("sig") or "").strip()
verified_name: str | None = None
if qp_from and qp_sig and _verify_signature(qp_from, qp_sig) and _is_known_colleague(qp_from):
verified_name = qp_from
if verified_name:
st.markdown(
f'<p style="margin:0 0 12px 0;color:#37474f;">'
f'From: <strong>{verified_name}</strong></p>',
unsafe_allow_html=True,
)
name = verified_name
else:
# No valid signature β†’ don't expose team names. Just take a
# free-text identifier so the recap can still attribute
# ("Team" if blank).
name = st.text_input(
"Your name (optional)",
placeholder="e.g. Sam Jones",
max_chars=80,
)
body = st.text_area(
"Feedback",
height=180,
placeholder=(
'Examples:\n'
' "More food manufacturing β€” Valeo, Compleat, Premier Foods."\n'
' "Bentley felt thin β€” already knew the story."\n'
' "Loved the Forward-Deployed Engineers theme β€” keep clustering AI-services patterns."'
),
)
submitted = st.button("Send feedback", type="primary", use_container_width=True)
if submitted:
ok, msg = _submit((name or "").strip(), body)
if ok:
st.success(msg)
st.markdown(
'<p style="text-align:center;color:#90a4ae;margin-top:24px;">'
'You can close this tab.</p>',
unsafe_allow_html=True,
)
else:
st.error(msg)