Guest invites provision immediately: remove the member approval gate

Operator decision 2026-11-08: the remaining protections (active member,
1 guest per inviter per rolling 30 days, one guest per recipient ever,
no existing portal row, MANUAL_MEMBERS refusal, the $2 cap and the
GUEST_DAYS box) are sufficient without the approval step.

* POST /broker/guests provisions through provision_guest_member at once —
  no pending state; no guest_requests row is ever written.
* GUEST_AUTO_APPROVE flag removed (the live env never carried it).
* guest_request_guard keeps the member-path rules and drops the
  trial-era pending-request checks; the 30-day window is counted from
  the guests ledger.
* GET /admin/guest-requests + approve/reject removed; GET /admin/guest-ledger
  serves the panel's duplicate-send guard.
* The member trail keeps legacy rejected requests as history only.

Built on the sibling $2-cap commit 6be8e2d.
This commit is contained in:
inference-bot committed 2026-11-08 20:20:30 +00:00
1 parent f1a86d9d76
commit 285aa66525
3 files changed
+195 -401

No files matched your search

+48 -206
View File
@@ -355,13 +355,12 @@ GUEST_PER_INVITER_DAYS = float(os.environ.get("GUEST_PER_INVITER_DAYS", "30"))
# guests ledger, and admin invites are NOT bound by the member's
# one-per-30-days cap (admins are not members).
ADMIN_INVITER_EMAIL = os.environ.get("ADMIN_INVITER_EMAIL", "info@inference.coop").strip().lower()
# Trial-period approval gate for MEMBER-initiated guest invitations. Off (the
# default): a member's request waits in PENDING until the operator approves or
# rejects it in the panel. On: a member's request provisions immediately,
# through the same pipeline and guards. Flipping it later is an env change,
# not a code change.
GUEST_AUTO_APPROVE = os.environ.get("GUEST_AUTO_APPROVE", "").strip().lower() in (
"1", "true", "yes", "on")
# MEMBER-initiated guest invitations provision IMMEDIATELY (operator decision,
# 2026-11-08 — the trial-era approval gate, including its GUEST_AUTO_APPROVE
# env flag, was removed). The guest pipeline's own guards are the protections:
# active-member inviter, one guest per inviter per rolling 30 days, one guest
# per recipient ever, no existing portal row, plus the member-path rule that
# the recipient is never a MANUAL_MEMBERS address.
# The Cloudron "guests" group: guest accounts land here. The chat and dashboard
# apps' access restrictions list BOTH members and guests, so a guest reaches
@@ -988,11 +987,11 @@ def get_db() -> sqlite3.Connection:
"guest_expires_at TEXT, "
"status TEXT DEFAULT 'active')"
)
# Guest REQUESTS — the member self-serve path's trial gate. A member's
# invitation lands here first; the operator approves (which fires the
# full guest pipeline and writes the ledger row above) or rejects it.
# PENDING requests are part of the abuse rules: they block the recipient
# address and count against the inviter's rolling window.
# Guest REQUESTS — LEGACY history from the trial-approval period. The
# approval gate was removed on 2026-11-08: a member's invitation
# provisions immediately, straight into the guests ledger above. The
# table is kept so the historical trail (decided requests) still reads;
# nothing writes to it any more.
conn.execute(
"CREATE TABLE IF NOT EXISTS guest_requests ("
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
@@ -1193,45 +1192,25 @@ def guest_provision_guard(
def guest_request_guard(conn, inviter_email: str, recipient_email: str) -> str | None:
"""Decide whether a MEMBER may send a guest invitation (pure).
Everything the guest pipeline enforces (guest_provision_guard: active
member inviter, one guest per inviter per rolling window, one guest per
recipient ever, no existing portal row) plus the member-path rules:
* the recipient is not on MANUAL_MEMBERS — manually-provisioned
accounts are co-op insiders, never guest targets;
* the recipient has no PENDING request already (from any inviter);
* the inviter's rolling GUEST_PER_INVITER_DAYS window counts REQUESTS
too — a pending or approved request sits inside the window, so the
one-per-30-days limit cannot be outrun by requesting twice while the
first is still waiting.
The member-invite guard. Runs everything guest_provision_guard enforces
(active member inviter, one guest per inviter per rolling window, one
guest per recipient ever, no existing portal row) plus the member-path
rule: the recipient is not on MANUAL_MEMBERS — manually-provisioned
accounts are co-op insiders, never guest targets.
A REJECTED request counts as neither: nothing was ever sent, and the
operator's gate still sits in front of every actual send.
(The trial-era pending-request rules are gone with the approval gate:
invitations provision immediately, and the one-per-30-days window is
counted from the guests ledger by guest_provision_guard.)
Returns None when the request may proceed, else a human-readable refusal.
Returns None when the invitation may proceed, else a human-readable refusal.
"""
refusal = guest_provision_guard(conn, inviter_email, recipient_email)
if refusal:
return refusal
inviter = (inviter_email or "").strip().lower()
recipient = (recipient_email or "").strip().lower()
if recipient in MANUAL_MEMBERS:
return ("That address belongs to a manually-provisioned co-op account — "
"guest invitations are for people outside the co-op")
pending = conn.execute(
"SELECT COUNT(*) FROM guest_requests WHERE recipient_email = ? AND status = 'pending'",
(recipient,),
).fetchone()[0]
if pending:
return f"{recipient} already has a guest request waiting for approval"
recent = conn.execute(
"SELECT COUNT(*) FROM guest_requests WHERE inviter_email = ? "
"AND status IN ('pending', 'approved') "
"AND created_at >= datetime('now', ?)",
(inviter, f"-{int(GUEST_PER_INVITER_DAYS)} days"),
).fetchone()[0]
if recent:
return (f"You already sent a guest request in the last "
f"{int(GUEST_PER_INVITER_DAYS)} days — one guest per member per month")
return None
@@ -4321,46 +4300,29 @@ async def admin_gift_convert_alias(request: Request):
# ---------------------------------------------------------------------------
# Guest-request approval (the member self-serve trial gate).
# Guests ledger (the approval gate was removed on 2026-11-08: member
# invitations provision immediately, so there is nothing to approve).
# ---------------------------------------------------------------------------
def _request_row(row) -> dict:
return {
"id": row[0], "inviter": row[1], "recipient": row[2],
"name": row[3], "created_at": row[4], "decided_at": row[5],
"status": row[6], "note": row[7],
}
@app.get("/admin/guest-requests")
@app.get("/admin/guest-ledger")
@limiter.limit("60/minute")
async def admin_guest_requests(request: Request):
"""The member guest-request queue and the guests ledger, for the panel.
async def admin_guest_ledger(request: Request):
"""The guests ledger, for the panel's duplicate-send guard.
Authenticated by the X-Admin-Token header. Returns the PENDING requests
awaiting the operator's decision (oldest first), the recently DECIDED
ones (approved/rejected, newest first), and the guests ledger itself —
one view where pending vs approved (and every later state) is visible.
Authenticated by the X-Admin-Token header. Returns the guests ledger
(inviter → recipient, newest first) so the panel can refuse a second
guest for an address that already holds an ACTIVE account BEFORE calling
/admin/provision-guest. The portal's own recipient-side guards remain
the last authority behind it.
"""
_verify_admin_token(request)
conn = get_db()
pending = conn.execute(
"SELECT id, inviter_email, recipient_email, recipient_name, created_at, "
"decided_at, status, note FROM guest_requests WHERE status = 'pending' ORDER BY id"
).fetchall()
decided = conn.execute(
"SELECT id, inviter_email, recipient_email, recipient_name, created_at, "
"decided_at, status, note FROM guest_requests WHERE status != 'pending' "
"ORDER BY id DESC LIMIT 100"
).fetchall()
ledger = conn.execute(
"SELECT id, inviter_email, recipient_email, created_at, status "
"FROM guests ORDER BY id DESC LIMIT 100"
).fetchall()
conn.close()
return {
"pending": [_request_row(r) for r in pending],
"decided": [_request_row(r) for r in decided],
"ledger": [
{"id": i, "inviter": inv, "recipient": rec, "created_at": created,
"status": status}
@@ -4369,92 +4331,6 @@ async def admin_guest_requests(request: Request):
}
@app.post("/admin/guest-requests/{request_id}/approve")
@limiter.limit("20/minute")
async def admin_guest_request_approve(request_id: int, request: Request):
"""Approve a pending guest request — the trial gate's approval action.
Approval fires the FULL guest pipeline (provision_guest_member: Cloudron
user, $2 credit, GUEST_DAYS box, invitation email naming the inviter,
newsletter subscribe, ledger row) — the same path the operator's
/admin/provision-guest runs, so every guard re-runs. If state moved since
the request (the recipient signed up; another invitation landed), the
refusal is recorded on the request and surfaced — the queue never
silently drops a decision.
"""
_verify_admin_token(request)
conn = get_db()
row = conn.execute(
"SELECT id, inviter_email, recipient_email, recipient_name, status "
"FROM guest_requests WHERE id = ?", (request_id,)
).fetchone()
conn.close()
if not row:
raise HTTPException(404, f"No guest request #{request_id}")
_, inviter, recipient, name, status = row
if status != "pending":
raise HTTPException(409, f"Request #{request_id} is already {status}")
try:
user_id = await provision_guest_member(
recipient, name or "", inviter)
except HTTPException as e:
conn = get_db()
conn.execute(
"UPDATE guest_requests SET status = 'rejected', "
"decided_at = datetime('now'), note = ? WHERE id = ?",
(str(e.detail), request_id),
)
conn.commit()
conn.close()
raise HTTPException(e.status_code, e.detail)
conn = get_db()
conn.execute(
"UPDATE guest_requests SET status = 'approved', "
"decided_at = datetime('now') WHERE id = ?", (request_id,)
)
conn.commit()
conn.close()
logger.info("Guest request #%s approved: %s invited %s (provisioned)",
request_id, inviter, recipient)
return {
"status": "approved", "request_id": request_id, "recipient": recipient,
"inviter": inviter, "user_id": user_id,
"budget": GUEST_BUDGET, "expires_in_days": int(GUEST_DAYS),
}
@app.post("/admin/guest-requests/{request_id}/reject")
@limiter.limit("20/minute")
async def admin_guest_request_reject(request_id: int, request: Request):
"""Reject a pending guest request (the trial gate's rejection action).
Nothing was ever sent to the recipient — no account, no email — so the
rejection tells only the INVITING member, through their own guest trail
(status 'not approved'). An optional note records why.
"""
_verify_admin_token(request)
body = await request.json() if request.headers.get("content-length", "0") not in ("", "0") else {}
note = (body.get("note") or "").strip() or None
conn = get_db()
row = conn.execute(
"SELECT id, status FROM guest_requests WHERE id = ?", (request_id,)
).fetchone()
if not row:
conn.close()
raise HTTPException(404, f"No guest request #{request_id}")
if row[1] != "pending":
conn.close()
raise HTTPException(409, f"Request #{request_id} is already {row[1]}")
conn.execute(
"UPDATE guest_requests SET status = 'rejected', "
"decided_at = datetime('now'), note = ? WHERE id = ?", (note, request_id)
)
conn.commit()
conn.close()
logger.info("Guest request #%s rejected", request_id)
return {"status": "rejected", "request_id": request_id, "note": note}
@app.post("/admin/org-link")
@limiter.limit("20/minute")
async def admin_org_link(request: Request):
@@ -6162,7 +6038,7 @@ async def broker_cancel_gift_alias(request: Request):
# ---------------------------------------------------------------------------
# Member self-serve guest invitations (trial gate: operator approval).
# Member self-serve guest invitations (provision immediately, 2026-11-08).
# ---------------------------------------------------------------------------
@app.get("/broker/guests")
@@ -6173,12 +6049,13 @@ async def broker_guest_list(request: Request):
Served through the member broker identity (a guest identity fails it —
only members invite guests). Returns:
* eligible / next_eligible_at — the rolling one-guest-per-member-per-
GUEST_PER_INVITER_DAYS rule, counting pending and approved REQUESTS
as well as sent guests (the same rule guest_request_guard enforces);
* trail — every invitation this member has made, newest first: pending
and rejected REQUESTS (an approved request IS its ledger row) plus
every row in the guests ledger with what became of it (active,
converted, expired, depleted, cancelled by recipient).
GUEST_PER_INVITER_DAYS rule, counted from the guests ledger (a
legacy approved request carries its own ledger row);
* trail — every invitation this member has made, newest first: legacy
REJECTED requests from the trial-approval period (kept for history;
nothing new is ever decided) plus every row in the guests ledger
with what became of it (active, converted, expired, depleted,
cancelled by recipient).
"""
email = _verify_broker_secret(request)
conn = get_db()
@@ -6193,19 +6070,13 @@ async def broker_guest_list(request: Request):
(email,),
).fetchall()
window = f"-{int(GUEST_PER_INVITER_DAYS)} days"
request_recent = conn.execute(
"SELECT MAX(created_at) FROM guest_requests WHERE inviter_email = ? "
"AND status IN ('pending', 'approved') AND created_at >= datetime('now', ?)",
(email, window),
).fetchone()[0]
ledger_recent = conn.execute(
last_sent = conn.execute(
"SELECT MAX(created_at) FROM guests WHERE inviter_email = ? "
"AND created_at >= datetime('now', ?)",
(email, window),
).fetchone()[0]
conn.close()
last_sent = max((t for t in (request_recent, ledger_recent) if t), default=None)
eligible = last_sent is None
next_eligible_at = None
if not eligible:
@@ -6217,7 +6088,7 @@ async def broker_guest_list(request: Request):
pass
trail = []
for rid, recipient, rname, created, decided, status, note in requests:
if status in ("pending", "rejected"):
if status == "rejected":
trail.append({
"kind": "request", "request_id": rid, "recipient": recipient,
"name": rname, "created_at": created, "decided_at": decided,
@@ -6231,7 +6102,6 @@ async def broker_guest_list(request: Request):
"eligible": eligible,
"per_inviter_days": int(GUEST_PER_INVITER_DAYS),
"next_eligible_at": next_eligible_at,
"auto_approve": bool(GUEST_AUTO_APPROVE),
"trail": trail,
}
@@ -6245,20 +6115,14 @@ async def broker_guest_invite(request: Request):
fails it, so only members reach here. Body: {"email": "<recipient>",
"name": "<optional display name>"}. Every protection runs BEFORE anything
is created (guest_request_guard): active-member inviter, one invitation
per member per rolling GUEST_PER_INVITER_DAYS (pending and approved
requests count), recipient never an existing member, a prior guest, a
pending request, or a MANUAL_MEMBERS address. The guest itself is
provisioned ONLY through provision_guest_member — the same pipeline the
operator's /admin/provision-guest runs (Cloudron user in the guests
group, $2 non-expiring credit, GUEST_DAYS time box, invitation email
naming the inviter, newsletter subscribe, ledger row).
Trial gate: with GUEST_AUTO_APPROVE off (the default) the request waits
in PENDING for the operator's approve/reject in the panel — nothing goes
to the recipient until it is approved, and the member sees 'pending
approval' in their dashboard trail. With it on, provisioning fires
immediately. The member is never emailed about a rejection; their trail
carries the status.
per member per rolling GUEST_PER_INVITER_DAYS, recipient never an existing
member or a prior guest, and never a MANUAL_MEMBERS address. A valid
invitation PROVISIONS IMMEDIATELY (operator decision, 2026-11-08 — the
trial-era approval gate is gone): provision_guest_member is the same
pipeline the operator's /admin/provision-guest runs (Cloudron user in the
guests group, $2 non-expiring credit, GUEST_DAYS time box, invitation
email naming the inviter, newsletter subscribe, ledger row) and re-runs
every guard, so a moved-state refusal still refuses.
"""
email = _verify_broker_secret(request)
body = await request.json()
@@ -6273,28 +6137,6 @@ async def broker_guest_invite(request: Request):
if refusal:
raise HTTPException(429, refusal)
if not GUEST_AUTO_APPROVE:
conn = get_db()
cur = conn.execute(
"INSERT INTO guest_requests (inviter_email, recipient_email, recipient_name) "
"VALUES (?, ?, ?)",
(email, recipient, name or None),
)
conn.commit()
request_id = cur.lastrowid
conn.close()
logger.info("Guest request #%s: %s invited %s (pending approval)",
request_id, email, recipient)
return {
"status": "pending_approval",
"request_id": request_id,
"recipient": recipient,
"name": name or None,
"note": ("Your guest request is waiting for a co-op approval. "
"Nothing has been sent yet — once it's approved, your "
"friend gets their account and invitation email, and "
"the status shows here."),
}
user_id = await provision_guest_member(recipient, name, email)
return {
"status": "provisioned", "account_type": "guest", "email": recipient,