Guest-invite form: outcome shown in the card, double-submit guard server-side

The operator could never tell what a submit did: the only outcome message was
the top flash, off-screen from the mid-page form, and a portal refusal left
the fields filled with nothing visible where the operator was looking.

- invite card now carries its own persistent status line (same palette as
  .flash): success 'Invite sent to <email> — expires <date>.' with the fields
  cleared; any refusal/failure shown plainly with the fields KEPT.
- button held disabled ('Sending…') for the whole request, restored after.
- flash(): clear the previous timer so a message shown soon after another is
  not hidden by the first message's timeout.
- SERVER-SIDE duplicate guard (guest_duplicate_refusal, pure + unit-tested):
  /api/provision-guest refuses 409 before any portal call when an ACTIVE
  guest for the email exists ('A guest account for <email> already exists')
  or a PENDING request awaits the decision ('awaits activation'). Holds for
  any client; the portal's own one-guest-per-recipient guard stays behind it.
- admin-panel-invite-harness.js pins the whole behavior.
This commit is contained in:
inference-bot committed 2026-11-08 03:12:30 +00:00
1 parent c16d044113
commit aabee20534
3 files changed
+269 -6

No files matched your search

+89 -6
View File
@@ -197,6 +197,40 @@ async def api_set_credits(request: Request):
return JSONResponse({"error": e.detail}, status_code=e.status_code)
def guest_duplicate_refusal(gq: dict, email: str) -> str | None:
"""Server-side duplicate-guest guard (pure — testable without FastAPI).
Decided from the portal's guest queues BEFORE any provisioning call, so a
double submit from ANY client (the panel form, a retry, a script) cannot
create a second account for the same recipient. Refuses when:
* an ACTIVE guest account for the email already exists (guests ledger
row with status 'active' — an expired/depleted row is not a live
account, so it falls through to the portal's authoritative
one-guest-per-recipient-ever refusal), or
* a PENDING member request for that email awaits the operator's
decision — the invitation "awaits activation"; approving that request
in the Guest requests tab, not a second send, is the way forward.
Returns the refusal message, or None when the request may proceed. The
portal's own recipient-side guard (one guest per recipient ever, no
existing portal row) remains the last authority behind this.
"""
recipient = (email or "").strip().lower()
if not recipient:
return None
for row in (gq.get("ledger") or []):
if ((row.get("recipient") or "").strip().lower() == recipient
and (row.get("status") or "").strip().lower() == "active"):
return (f"A guest account for {recipient} already exists — "
"no second account was created")
for row in (gq.get("pending") or []):
if (row.get("recipient") or "").strip().lower() == recipient:
return (f"A guest invitation for {recipient} already awaits activation — "
"approve or reject it in the Guest requests tab instead of "
"sending a second invite")
return None
@app.post("/api/provision-guest")
async def api_provision_guest(request: Request):
"""Provision a guest account via the portal's /admin/provision-guest.
@@ -209,6 +243,12 @@ async def api_provision_guest(request: Request):
by the member's one-per-30-days cap, and the recipient-side guards (one
guest per recipient ever, no existing portal row) still run there. A
refusal is surfaced to the operator as-is.
A server-side duplicate guard runs HERE, before the portal call: an
active guest or a pending request for the same email is refused with a
specific message instead of a second account being created (the form's
disable-while-sending only guards this one page; this guard holds for
any client).
"""
if not is_admin(request):
return JSONResponse({"error": "forbidden"}, status_code=403)
@@ -217,6 +257,13 @@ async def api_provision_guest(request: Request):
name = (body.get("name") or "").strip()
if not email or "@" not in email:
return JSONResponse({"error": "A valid recipient email is required"}, status_code=400)
try:
gq = await portal_get("/admin/guest-requests")
except HTTPException:
gq = {} # queues unreadable — fall through; the portal's own guard still runs
refusal = guest_duplicate_refusal(gq, email)
if refusal:
return JSONResponse({"error": refusal}, status_code=409)
try:
return await portal_post("/admin/provision-guest", {"email": email, "name": name})
except HTTPException as e:
@@ -376,6 +423,12 @@ PAGE_HTML = """<!DOCTYPE html>
.guest-invite-btn { cursor: pointer; border: none; border-radius: 8px; background: var(--green-deep); color: #fff; font-size: 13px; font-weight: 600; padding: 10px 16px; align-self: flex-start; }
.guest-invite-btn:hover { background: #4e7a4d; }
.guest-invite-btn:disabled { opacity: 0.6; cursor: default; }
/* Outcome of a submit, shown INSIDE the card (the top flash sits above the
tabs — off-screen from a mid-page form — so an outcome only there is one
the operator never sees). Same palette as the .flash styles. */
.guest-invite-status { display: none; margin-top: 10px; padding: 10px 14px; border-radius: 8px; font-size: 13px; max-width: 420px; }
.guest-invite-status.ok { display: block; background: #eaf3ea; color: #2f5c30; }
.guest-invite-status.err { display: block; background: #f6e9e5; color: var(--danger); }
@media (max-width: 600px) { .guest-invite-btn { align-self: stretch; } }
/* Trends tab (charts). Colours come from the same vars as the rest of the
panel; the SVG is inline so there is no chart library and no CDN. */
@@ -498,6 +551,7 @@ PAGE_HTML = """<!DOCTYPE html>
<input id="guest-name" type="text" maxlength="80" autocomplete="off" placeholder="Only if you know it" />
<button type="submit" class="guest-invite-btn" id="guest-send">Send invite</button>
</form>
<div class="guest-invite-status" id="guest-invite-status" role="status" aria-live="polite"></div>
</div>
</div>
@@ -672,11 +726,24 @@ PAGE_HTML = """<!DOCTYPE html>
<script>
const $ = (id) => document.getElementById(id);
let flashTimer = null;
function flash(msg, ok) {
const f = $('flash');
f.textContent = msg;
f.className = 'flash show ' + (ok ? 'ok' : 'err');
setTimeout(() => { f.className = 'flash'; }, 6000);
// Clear the previous timer first, or a message shown soon after another is
// hidden by the FIRST message's timeout (hidden long before its own 6s).
if (flashTimer) clearTimeout(flashTimer);
flashTimer = setTimeout(() => { f.className = 'flash'; }, 6000);
}
// The invite card's OWN status line — the outcome where the operator is
// looking. Unlike the top flash it does NOT auto-hide: a submit's outcome
// should still be readable when the operator looks back at the form.
function inviteStatus(msg, ok) {
const s = $('guest-invite-status');
s.textContent = msg;
s.className = 'guest-invite-status ' + (ok ? 'ok' : 'err');
}
function fmt(n) { const v = Math.abs(Number(n)) < 0.005 ? 0 : (Number(n) || 0); return '$' + v.toFixed(2); }
@@ -1485,12 +1552,21 @@ async function addBalance(email) {
// the portal; admins have no monthly cap. The portal enforces the
// recipient-side guards (one guest per recipient ever, no existing portal
// row) and reports a clear refusal.
//
// Submit UX (the operator must always be able to tell what happened):
// * the button is disabled with "Sending…" for the whole request — a double
// click cannot fire a second invite while the first is in flight;
// * SUCCESS: the fields are cleared and the outcome is stated in the card
// itself — 'Invite sent to <email> — expires <date>.' (the guests list
// refreshes underneath, so the new account is visible too);
// * FAILURE: the error is shown plainly in the card (and the top flash),
// and the fields are KEPT so the operator can correct and retry.
async function sendGuestAccess(ev) {
if (ev) ev.preventDefault();
const email = ($('guest-email').value || '').trim();
const name = ($('guest-name').value || '').trim();
const btn = $('guest-send');
if (!email || email.indexOf('@') < 1) { flash("Enter the guest's email", false); return; }
if (!email || email.indexOf('@') < 1) { inviteStatus("Enter the guest's email", false); flash("Enter the guest's email", false); return; }
btn.disabled = true; btn.textContent = "Sending…";
try {
const r = await fetch('/api/provision-guest', {
@@ -1498,12 +1574,19 @@ async function sendGuestAccess(ev) {
body: JSON.stringify({ email, name })
});
const d = await r.json().catch(() => ({}));
if (!r.ok || d.error) { flash(d.error || ('Could not send guest access (' + r.status + ')'), false); return; }
flash('Invite sent — ' + email + ' has $5 of credits (expires in ' + (d.expires_in_days || 60) +
' days). The welcome email is on its way.', true);
if (!r.ok || d.error) {
const msg = d.error || ('Could not send guest access (' + r.status + ')');
inviteStatus(msg, false); flash(msg, false);
return;
}
const days = d.expires_in_days || 60;
const exp = new Date(Date.now() + days * 86400000)
.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
const msg = 'Invite sent to ' + email + ' — expires ' + exp + '.';
inviteStatus(msg, true); flash(msg, true);
$('guest-email').value = ''; $('guest-name').value = '';
load();
} catch (e) { flash('Guest access failed: ' + e.message, false); }
} catch (e) { const msg = 'Guest access failed: ' + e.message; inviteStatus(msg, false); flash(msg, false); }
finally { btn.disabled = false; btn.textContent = 'Send invite'; }
}