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

+108
View File
@@ -0,0 +1,108 @@
// Harness for the admin panel's GUEST-INVITE form (sendGuestAccess), run via
// the skill's checker:
// ~/.hermes/skills/research/inference-cooperative/scripts/check-page-js.sh \
// app/main.py admin-panel-invite-harness.js
// The operator could never tell what a submit did (no clearing, no message),
// so the harness pins the behavior the fix promises:
// * the button is DISABLED for the whole request ("Sending…") — a double
// click cannot fire a second invite mid-flight;
// * SUCCESS: the fields are cleared and the card states
// 'Invite sent to <email> — expires <date>.' (and the guests list reloads);
// * REFUSAL (duplicate guard): the error is shown plainly in the card and
// the fields are KEPT (no silent swallow, no accidental re-clear);
// * the button is re-enabled afterwards in every path.
const assert = (cond, msg) => { if (!cond) { console.error("FAIL: " + msg); process.exit(1); } };
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const txt = (id) => String(document.getElementById(id).textContent);
const cls = (id) => String(document.getElementById(id).className);
const val = (id) => String(document.getElementById(id).value);
function typeInvite(email, name) {
document.getElementById("guest-email").value = email;
document.getElementById("guest-name").value = name || "";
}
// Responder queue: each fetch consumes the next entry — a function that,
// given the resolved body, returns the response object {status, json}.
// `during` runs INSIDE the fetch promise — the moment the request is in
// flight — to observe the form state.
let responders = [];
let duringFlight = null;
let loadCalled = 0;
globalThis.fetch = async (url, opts) => {
if (String(url).indexOf("/api/overview") !== -1) {
loadCalled++;
return { status: 200, json: async () => ({ members: [], guests: [], totals: { members: 0 } }) };
}
const body = JSON.parse((opts && opts.body) || "{}");
const r = responders.shift();
if (duringFlight) duringFlight();
return r(body);
};
const ok200 = (payload) => ({ status: 200, ok: true, json: async () => payload });
const bad = (status, payload) => ({ status, ok: false, json: async () => payload });
(async () => {
// ---- SUCCESS: fields cleared, dated success message, button held+released --
responders = [() => ok200({ status: "provisioned", email: "friend@example.com", expires_in_days: 60 })];
typeInvite("friend@example.com", "Friend");
let sawDisabled = false;
duringFlight = () => {
sawDisabled = document.getElementById("guest-send").disabled === true;
};
await sendGuestAccess({ preventDefault() {} });
duringFlight = null;
assert(sawDisabled, "button is disabled while the request is in flight");
assert(txt("guest-send") === "Send invite", "button label restored after success (got " + txt("guest-send") + ")");
assert(val("guest-email") === "", "email field cleared after success (got " + val("guest-email") + ")");
assert(val("guest-name") === "", "name field cleared after success (got " + val("guest-name") + ")");
const okMsg = txt("guest-invite-status");
assert(okMsg.indexOf("Invite sent to friend@example.com") === 0,
"success message names the recipient (got " + JSON.stringify(okMsg) + ")");
assert(okMsg.indexOf("— expires ") !== -1 && okMsg.endsWith("."),
"success message carries an expiry date (got " + JSON.stringify(okMsg) + ")");
assert(cls("guest-invite-status").indexOf("ok") !== -1, "success status styled ok");
assert(cls("flash").indexOf("ok") !== -1, "top flash also reports success");
assert(loadCalled >= 1, "the guests list reloads after a successful invite");
// ---- REFUSAL (duplicate guard): error shown plainly, fields KEPT -----------
responders = [() => bad(409, { error: "A guest account for friend@example.com already exists — no second account was created" })];
typeInvite("friend@example.com", "Friend");
await sendGuestAccess({ preventDefault() {} });
const errMsg = txt("guest-invite-status");
assert(errMsg.indexOf("A guest account for friend@example.com already exists") === 0,
"duplicate refusal shown verbatim in the card (got " + JSON.stringify(errMsg) + ")");
assert(cls("guest-invite-status").indexOf("err") !== -1, "refusal styled as an error");
assert(val("guest-email") === "friend@example.com", "email KEPT on refusal");
assert(val("guest-name") === "Friend", "name KEPT on refusal");
assert(txt("guest-send") === "Send invite", "button re-enabled after refusal");
assert(txt("flash").indexOf("already exists") !== -1, "top flash carries the refusal too");
// ---- HTTP-level failure (no error body): message, fields kept --------------
responders = [() => bad(502, {})];
typeInvite("other@example.com", "");
await sendGuestAccess({ preventDefault() {} });
assert(txt("guest-invite-status").indexOf("Could not send guest access") === 0,
"transport failure reported in the card (got " + JSON.stringify(txt("guest-invite-status")) + ")");
assert(val("guest-email") === "other@example.com", "email kept on transport failure");
// ---- Network error: reported, fields kept ----------------------------------
responders = [() => { throw new Error("boom"); }];
typeInvite("third@example.com", "");
await sendGuestAccess({ preventDefault() {} });
assert(txt("guest-invite-status").indexOf("Guest access failed: boom") === 0,
"network failure reported in the card (got " + JSON.stringify(txt("guest-invite-status")) + ")");
assert(val("guest-email") === "third@example.com", "email kept on network error");
// ---- Missing email: refused locally, nothing sent --------------------------
responders = []; // any fetch here would be an unwanted POST
typeInvite("", "");
await sendGuestAccess({ preventDefault() {} });
assert(txt("guest-invite-status").indexOf("Enter the guest's email") === 0,
"blank email refused locally (got " + JSON.stringify(txt("guest-invite-status")) + ")");
assert(responders.length === 0, "no request fired for a blank email");
console.log("invite harness: all assertions passed");
})().catch((e) => { console.error("FAIL: " + (e && e.stack || e)); process.exit(1); });
+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'; }
}
+72
View File
@@ -0,0 +1,72 @@
# The admin panel's SERVER-SIDE duplicate-guest guard (app/main.py
# guest_duplicate_refusal). The function is pure (no FastAPI/state), so the
# test extracts it from the source and runs it the same way check-page-js.sh
# treats the page JS — slicing, not importing (importing app.main pulls in
# app.oidc → authlib, which the steward host does not have).
#
# Run: python3 tests/test_guest_guard.py
import re
import sys
from pathlib import Path
SRC = Path(__file__).resolve().parent.parent / "app" / "main.py"
start = SRC.read_text().index("def guest_duplicate_refusal(")
end = SRC.read_text().index("\n@app.post(", start)
ns: dict = {}
exec(SRC.read_text()[start:end], ns)
guard = ns["guest_duplicate_refusal"]
failures = []
def check(name, got, want):
if got != want:
failures.append(f"{name}: got {got!r}, want {want!r}")
else:
print(f"ok - {name}")
LEDGER_ACTIVE = [{"id": 3, "inviter": "info@inference.coop",
"recipient": "friend@example.com", "status": "active"}]
LEDGER_LAPSED = [{"id": 3, "inviter": "info@inference.coop",
"recipient": "friend@example.com", "status": "expired"}]
PENDING_REQ = [{"id": 7, "inviter": "alice@example.com",
"recipient": "someone@example.com", "status": "pending"}]
EMPTY = {"ledger": [], "pending": []}
# An ACTIVE guest for the email → refuse, message names the email.
refusal = guard({"ledger": LEDGER_ACTIVE, "pending": []}, "friend@example.com")
check("active guest refused", refusal is not None and refusal.startswith(
"A guest account for friend@example.com already exists"), True)
check("active refusal states no second account",
"no second account" in (refusal or ""), True)
# Case/whitespace of the submitted email must not dodge the match.
check("case-insensitive match", guard({"ledger": LEDGER_ACTIVE, "pending": []},
" Friend@Example.COM ") is not None, True)
# A PENDING member request for the email → refuse as "awaits activation".
refusal = guard({"ledger": [], "pending": PENDING_REQ}, "someone@example.com")
check("pending request refused", refusal is not None and
"awaits activation" in refusal and "someone@example.com" in refusal, True)
# Lapsed (expired/depleted) ledger row is NOT a live account: no panel-side
# refusal — the portal's one-guest-per-recipient-ever guard is the authority.
check("expired ledger row falls through",
guard({"ledger": LEDGER_LAPSED, "pending": []}, "friend@example.com"), None)
# Someone else's guest/request never blocks a new address.
check("other recipients ignored",
guard({"ledger": LEDGER_ACTIVE, "pending": PENDING_REQ}, "new@example.com"), None)
# Empty/missing queues (portal unreadable → guard falls through, never blocks).
check("empty queues pass", guard(EMPTY, "friend@example.com"), None)
check("missing keys pass", guard({}, "friend@example.com"), None)
check("blank email passes (route validates first)", guard(EMPTY, ""), None)
if failures:
print("\nFAILURES:")
for f in failures:
print(" " + f)
sys.exit(1)
print("\nAll guest_duplicate_refusal checks passed.")