From aabee20534b03442327d332223d14bd098b51431 Mon Sep 17 00:00:00 2001 From: Inferencebot Date: Sun, 8 Nov 2026 03:12:30 +0000 Subject: [PATCH] Guest-invite form: outcome shown in the card, double-submit guard server-side MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 — expires .' 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 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. --- admin-panel-invite-harness.js | 108 ++++++++++++++++++++++++++++++++++ app/main.py | 95 ++++++++++++++++++++++++++++-- tests/test_guest_guard.py | 72 +++++++++++++++++++++++ 3 files changed, 269 insertions(+), 6 deletions(-) create mode 100644 admin-panel-invite-harness.js create mode 100644 tests/test_guest_guard.py diff --git a/admin-panel-invite-harness.js b/admin-panel-invite-harness.js new file mode 100644 index 0000000..75f6eef --- /dev/null +++ b/admin-panel-invite-harness.js @@ -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 — expires .' (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); }); diff --git a/app/main.py b/app/main.py index 2c029eb..8b0168e 100644 --- a/app/main.py +++ b/app/main.py @@ -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 = """ .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 = """ +
@@ -672,11 +726,24 @@ PAGE_HTML = """