Remove the pending guest-requests section — nothing to approve anymore

The portal provisions member invites immediately (approval gate removed
2026-11-08), so the panel drops the Guest requests tab (queue, decisions,
badge and their JS) and the approve/reject API hops. Kept: the Guests list
(member-invited guests show inviter, credits, expiry, status, same as
admin-created ones) and the duplicate-send guard, now fed by the portal's
GET /admin/guest-ledger (ledger only — no pending key). Test updated: the
guard no longer has a pending branch; a legacy pending-shaped payload is
inert.
This commit is contained in:
inference-bot committed 2026-11-08 20:20:33 +00:00
1 parent 74165f1957
commit f9c2ae6417
2 files changed
+46 -233

No files matched your search

+26 -219
View File
@@ -200,16 +200,13 @@ async def api_set_credits(request: Request):
def guest_duplicate_refusal(gq: dict, email: str) -> str | None: def guest_duplicate_refusal(gq: dict, email: str) -> str | None:
"""Server-side duplicate-guest guard (pure — testable without FastAPI). """Server-side duplicate-guest guard (pure — testable without FastAPI).
Decided from the portal's guest queues BEFORE any provisioning call, so a Decided from the portal's guests ledger BEFORE any provisioning call, so
double submit from ANY client (the panel form, a retry, a script) cannot a double submit from ANY client (the panel form, a retry, a script)
create a second account for the same recipient. Refuses when: cannot create a second account for the same recipient. Refuses when an
* an ACTIVE guest account for the email already exists (guests ledger ACTIVE guest account for the email already exists (guests ledger row with
row with status 'active' — an expired/depleted row is not a live status 'active' — an expired/depleted row is not a live account, so it
account, so it falls through to the portal's authoritative falls through to the portal's authoritative one-guest-per-recipient-ever
one-guest-per-recipient-ever refusal), or refusal).
* 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 Returns the refusal message, or None when the request may proceed. The
portal's own recipient-side guard (one guest per recipient ever, no portal's own recipient-side guard (one guest per recipient ever, no
@@ -223,11 +220,6 @@ def guest_duplicate_refusal(gq: dict, email: str) -> str | None:
and (row.get("status") or "").strip().lower() == "active"): and (row.get("status") or "").strip().lower() == "active"):
return (f"A guest account for {recipient} already exists — " return (f"A guest account for {recipient} already exists — "
"no second account was created") "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 return None
@@ -245,8 +237,8 @@ async def api_provision_guest(request: Request):
refusal is surfaced to the operator as-is. refusal is surfaced to the operator as-is.
A server-side duplicate guard runs HERE, before the portal call: an 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 active guest for the same email is refused with a specific message
specific message instead of a second account being created (the form's instead of a second account being created (the form's
disable-while-sending only guards this one page; this guard holds for disable-while-sending only guards this one page; this guard holds for
any client). any client).
""" """
@@ -258,9 +250,9 @@ async def api_provision_guest(request: Request):
if not email or "@" not in email: if not email or "@" not in email:
return JSONResponse({"error": "A valid recipient email is required"}, status_code=400) return JSONResponse({"error": "A valid recipient email is required"}, status_code=400)
try: try:
gq = await portal_get("/admin/guest-requests") gq = await portal_get("/admin/guest-ledger")
except HTTPException: except HTTPException:
gq = {} # queues unreadable — fall through; the portal's own guard still runs gq = {} # ledger unreadable — fall through; the portal's own guard still runs
refusal = guest_duplicate_refusal(gq, email) refusal = guest_duplicate_refusal(gq, email)
if refusal: if refusal:
return JSONResponse({"error": refusal}, status_code=409) return JSONResponse({"error": refusal}, status_code=409)
@@ -270,49 +262,19 @@ async def api_provision_guest(request: Request):
return JSONResponse({"error": e.detail}, status_code=e.status_code) return JSONResponse({"error": e.detail}, status_code=e.status_code)
@app.get("/api/guest-requests") @app.get("/api/guest-ledger")
async def api_guest_requests(request: Request): async def api_guest_ledger(request: Request):
"""The member guest-request queue + the guests ledger (portal /admin/guest-requests). """The guests ledger (portal /admin/guest-ledger).
The member self-serve path's trial gate: PENDING requests wait here for Every guest access sent and what became of it — the feed behind the
the operator's approve/reject; the ledger shows every sent guest and what duplicate-send guard. (The member guest-request queue is GONE with the
became of it — pending vs approved visible in one view. approval gate, removed 2026-11-08: member invitations provision
immediately, so there is nothing to approve.)
""" """
if not is_admin(request): if not is_admin(request):
return JSONResponse({"error": "forbidden"}, status_code=403) return JSONResponse({"error": "forbidden"}, status_code=403)
try: try:
return await portal_get("/admin/guest-requests") return await portal_get("/admin/guest-ledger")
except HTTPException as e:
return JSONResponse({"error": e.detail}, status_code=e.status_code)
@app.post("/api/guest-requests/{request_id}/approve")
async def api_guest_request_approve(request_id: int, request: Request):
"""Approve a pending guest request — fires the full guest provisioning.
One hop to the portal's /admin/guest-requests/{id}/approve, which runs
the same pipeline as the operator's own guest action and re-checks every
guard (state may have moved since the member made the request).
"""
if not is_admin(request):
return JSONResponse({"error": "forbidden"}, status_code=403)
try:
return await portal_post(f"/admin/guest-requests/{request_id}/approve", {})
except HTTPException as e:
return JSONResponse({"error": e.detail}, status_code=e.status_code)
@app.post("/api/guest-requests/{request_id}/reject")
async def api_guest_request_reject(request_id: int, request: Request):
"""Reject a pending guest request. Nothing has gone to the recipient;
the inviting member sees 'not approved' in their own dashboard trail."""
if not is_admin(request):
return JSONResponse({"error": "forbidden"}, status_code=403)
body = await request.json() if (request.headers.get("content-length") or "0") != "0" else {}
note = (body.get("note") or "").strip()
try:
return await portal_post(f"/admin/guest-requests/{request_id}/reject",
{"note": note} if note else {})
except HTTPException as e: except HTTPException as e:
return JSONResponse({"error": e.detail}, status_code=e.status_code) return JSONResponse({"error": e.detail}, status_code=e.status_code)
@@ -508,7 +470,6 @@ PAGE_HTML = """<!DOCTYPE html>
<button class="tab-btn" id="tab-models" onclick="switchView('models')">Model usage</button> <button class="tab-btn" id="tab-models" onclick="switchView('models')">Model usage</button>
<button class="tab-btn" id="tab-trends" onclick="switchView('trends')">Trends</button> <button class="tab-btn" id="tab-trends" onclick="switchView('trends')">Trends</button>
<button class="tab-btn" id="tab-money" onclick="switchView('money')">Money</button> <button class="tab-btn" id="tab-money" onclick="switchView('money')">Money</button>
<button class="tab-btn" id="tab-guestrequests" onclick="switchView('guestrequests')">Guest requests<span id="guestreq-badge" style="display:none;"></span></button>
<span class="range-group" id="member-mode-group"> <span class="range-group" id="member-mode-group">
<button class="range-btn active" id="mmode-balance" onclick="setMemberMode('balance')">Balance</button> <button class="range-btn active" id="mmode-balance" onclick="setMemberMode('balance')">Balance</button>
<button class="range-btn" id="mmode-all" onclick="setMemberMode('all')">All time</button> <button class="range-btn" id="mmode-all" onclick="setMemberMode('all')">All time</button>
@@ -622,56 +583,6 @@ PAGE_HTML = """<!DOCTYPE html>
</div> </div>
</div> </div>
<div id="guestrequests-section" style="display:none;">
<h3 style="margin:20px 0 8px;">Pending guest requests</h3>
<p style="color:var(--muted);font-size:12px;margin:0 0 8px;">Member-initiated guest invitations waiting for a decision. Approve runs the full guest pipeline ($2 credit, 60-day box, invitation email naming the inviting member); nothing has gone to the recipient before approval. Reject tells the inviting member 'not approved' in their own dashboard trail.</p>
<div class="table-scroll">
<table id="table-guestrequests">
<thead>
<tr>
<th>Requested</th>
<th>Inviting member</th>
<th>Recipient</th>
<th>Name</th>
<th>Decision</th>
</tr>
</thead>
<tbody id="guestrequest-rows"><tr><td colspan="5" style="color:var(--muted)">Loading…</td></tr></tbody>
</table>
</div>
<h3 style="margin:26px 0 8px;">Recent decisions</h3>
<div class="table-scroll">
<table id="table-guestdecisions">
<thead>
<tr>
<th>Requested</th>
<th>Inviting member</th>
<th>Recipient</th>
<th>Decided</th>
<th>Status</th>
<th>Note</th>
</tr>
</thead>
<tbody id="guestdecision-rows"></tbody>
</table>
</div>
<h3 style="margin:26px 0 8px;">Guests ledger</h3>
<p style="color:var(--muted);font-size:12px;margin:0 0 8px;">Every guest access sent, and what became of it. Members' requests appear above before they enter this ledger — pending vs approved in one view.</p>
<div class="table-scroll">
<table id="table-guestledger">
<thead>
<tr>
<th>Sent</th>
<th>Inviting member</th>
<th>Recipient</th>
<th>Status</th>
</tr>
</thead>
<tbody id="guestledger-rows"></tbody>
</table>
</div>
</div>
<div id="agents-section" style="display:none;"> <div id="agents-section" style="display:none;">
<h3 style="margin:20px 0 8px;">Agents</h3> <h3 style="margin:20px 0 8px;">Agents</h3>
<p style="color:var(--muted);font-size:12px;margin:0 0 8px;">Bot and sandbox accounts. Not members — excluded from member counts; their usage is a collective expense.</p> <p style="color:var(--muted);font-size:12px;margin:0 0 8px;">Bot and sandbox accounts. Not members — excluded from member counts; their usage is a collective expense.</p>
@@ -1287,13 +1198,11 @@ function switchView(view) {
$('agents-section').style.display = view === 'members' ? '' : 'none'; $('agents-section').style.display = view === 'members' ? '' : 'none';
$('trends-section').style.display = view === 'trends' ? '' : 'none'; $('trends-section').style.display = view === 'trends' ? '' : 'none';
$('money-section').style.display = view === 'money' ? '' : 'none'; $('money-section').style.display = view === 'money' ? '' : 'none';
$('guestrequests-section').style.display = view === 'guestrequests' ? '' : 'none';
$('tab-members').className = 'tab-btn' + (view === 'members' ? ' active' : ''); $('tab-members').className = 'tab-btn' + (view === 'members' ? ' active' : '');
$('tab-models').className = 'tab-btn' + (view === 'models' ? ' active' : ''); $('tab-models').className = 'tab-btn' + (view === 'models' ? ' active' : '');
$('tab-trends').className = 'tab-btn' + (view === 'trends' ? ' active' : ''); $('tab-trends').className = 'tab-btn' + (view === 'trends' ? ' active' : '');
$('tab-money').className = 'tab-btn' + (view === 'money' ? ' active' : ''); $('tab-money').className = 'tab-btn' + (view === 'money' ? ' active' : '');
$('tab-guestrequests').className = 'tab-btn' + (view === 'guestrequests' ? ' active' : ''); $('view-title').textContent = view === 'members' ? 'Members' : (view === 'models' ? 'Model usage' : (view === 'trends' ? 'Trends' : 'Money'));
$('view-title').textContent = view === 'members' ? 'Members' : (view === 'models' ? 'Model usage' : (view === 'trends' ? 'Trends' : (view === 'money' ? 'Money' : 'Guest requests')));
// Mode groups: Balance/All-time for members; Period for models; the guest // Mode groups: Balance/All-time for members; Period for models; the guest
// invite form belongs to the members view too. // invite form belongs to the members view too.
$('range-group').style.display = view === 'models' ? '' : 'none'; $('range-group').style.display = view === 'models' ? '' : 'none';
@@ -1304,9 +1213,6 @@ function switchView(view) {
// Money renders on first visit only, same rule: one fetch, then the // Money renders on first visit only, same rule: one fetch, then the
// period/spend toggles re-render client-side. // period/spend toggles re-render client-side.
if (view === 'money') loadMoney(); if (view === 'money') loadMoney();
// The guest-request queue refetches on EVERY visit and after every
// decision — a queue the operator acts on must never show stale rows.
if (view === 'guestrequests') loadGuestRequests();
render(); render();
} }
@@ -1590,114 +1496,15 @@ async function sendGuestAccess(ev) {
finally { btn.disabled = false; btn.textContent = 'Send invite'; } finally { btn.disabled = false; btn.textContent = 'Send invite'; }
} }
// ---- Guest requests: the member self-serve trial gate ---------------------- // ---- Guest requests: REMOVED (2026-11-08) ----------------------------------
// The queue refetches on every tab visit and after every decision, so a row // The member self-serve approval gate is gone — member invitations provision
// the operator is about to act on is never stale. The ledger surfaces every // immediately in the portal, so there is nothing to approve or reject here.
// sent guest — pending vs approved (and every later state) in one view. // The Guests list (members view) shows every member-invited guest with its
// inviter, credits, expiry and status, exactly like admin-created ones.
function grDay(s) { // The portal's /admin/guest-ledger still feeds the duplicate-send guard.
if (!s) return '—';
const d = new Date(String(s).replace(' ', 'T') + (String(s).includes('Z') ? '' : 'Z'));
return isNaN(d) ? String(s).slice(0, 10) : d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
}
function grPill(status) {
const map = {
pending: ['pending', 'grace', 'Waiting for the operator'],
approved: ['approved', 'active', 'Provisioned — the guest pipeline ran'],
rejected: ['rejected', 'inactive', 'Declined — the inviting member sees this in their trail'],
active: ['active', 'guest', 'Guest account live'],
converted:['converted', 'manual', 'The guest became a member'],
expired: ['expired', 'inactive', 'Time box ran out'],
depleted: ['depleted', 'inactive', 'The $2 credit was spent'],
'cancelled by recipient': ['cancelled', 'inactive', 'Ended at the recipient\u2019s own request'],
};
const [label, cls, title] = map[status] || [status || '—', 'grace', ''];
return '<span class="pill ' + cls + '"' + (title ? ' title="' + esc(title) + '"' : '') + '>' + esc(label) + '</span>';
}
function setGuestReqBadge(n) {
const b = $('guestreq-badge');
if (!b) return;
b.style.display = n > 0 ? '' : 'none';
b.textContent = n > 0 ? ' (' + n + ')' : '';
}
async function loadGuestRequests() {
try {
const r = await fetch('/api/guest-requests');
const d = await r.json().catch(() => ({}));
if (!r.ok || d.error) {
flash('Could not load guest requests: ' + (d.error || r.status), false);
return;
}
setGuestReqBadge((d.pending || []).length);
const rows = d.pending || [];
$('guestrequest-rows').innerHTML = rows.length ? rows.map(q =>
'<tr>' +
'<td>' + grDay(q.created_at) + '</td>' +
'<td>' + esc(q.inviter || '—') + '</td>' +
'<td><strong>' + esc(q.recipient || '—') + '</strong></td>' +
'<td>' + esc(q.name || '—') + '</td>' +
'<td><span class="adjust">' +
'<button onclick="approveGuestRequest(' + q.id + ', this)">Approve</button>' +
'<button class="credits-btn" onclick="rejectGuestRequest(' + q.id + ', this)">Reject</button>' +
'</span></td>' +
'</tr>'
).join('') : '<tr><td colspan="5" style="color:var(--muted)">No pending guest requests.</td></tr>';
const dec = d.decided || [];
$('guestdecision-rows').innerHTML = dec.length ? dec.map(q =>
'<tr>' +
'<td>' + grDay(q.created_at) + '</td>' +
'<td>' + esc(q.inviter || '—') + '</td>' +
'<td>' + esc(q.recipient || '—') + '</td>' +
'<td>' + grDay(q.decided_at) + '</td>' +
'<td>' + grPill(q.status) + '</td>' +
'<td>' + esc(q.note || '') + '</td>' +
'</tr>'
).join('') : '<tr><td colspan="6" style="color:var(--muted)">No decisions yet.</td></tr>';
const led = d.ledger || [];
$('guestledger-rows').innerHTML = led.length ? led.map(l =>
'<tr>' +
'<td>' + grDay(l.created_at) + '</td>' +
'<td>' + esc(l.inviter || '—') + '</td>' +
'<td>' + esc(l.recipient || '—') + '</td>' +
'<td>' + grPill(l.status) + '</td>' +
'</tr>'
).join('') : '<tr><td colspan="4" style="color:var(--muted)">The guests ledger is empty.</td></tr>';
} catch (e) {
flash('Could not load guest requests: ' + e.message, false);
}
}
async function approveGuestRequest(id, btn) {
if (!window.confirm('Approve this guest request? The account is created, the $2 credit is granted and the invitation email goes out to the recipient.')) return;
btn.disabled = true;
try {
const r = await fetch('/api/guest-requests/' + id + '/approve', { method: 'POST' });
const d = await r.json().catch(() => ({}));
if (!r.ok || d.error) { flash(d.error || ('Approval failed (' + r.status + ')'), false); }
else { flash('Approved — ' + d.recipient + ' is provisioned ($2 credit, ' + (d.expires_in_days || 60) + '-day box). The invitation email is on its way.', true); }
} catch (e) { flash('Approval failed: ' + e.message, false); }
await loadGuestRequests();
load(); // a new guest row changes the guests list + counts
}
async function rejectGuestRequest(id, btn) {
if (!window.confirm('Reject this guest request? Nothing has been sent to the recipient; the inviting member will see "not approved" in their dashboard.')) return;
btn.disabled = true;
try {
const r = await fetch('/api/guest-requests/' + id + '/reject', { method: 'POST' });
const d = await r.json().catch(() => ({}));
if (!r.ok || d.error) { flash(d.error || ('Rejection failed (' + r.status + ')'), false); }
else { flash('Request rejected — nothing was sent to the recipient.', true); }
} catch (e) { flash('Rejection failed: ' + e.message, false); }
await loadGuestRequests();
}
load(); load();
loadModels(); loadModels();
loadGuestRequests(); // badge the tab with the pending count at startup
</script> </script>
</body> </body>
</html>""" </html>"""
+20 -14
View File
@@ -4,6 +4,11 @@
# treats the page JS — slicing, not importing (importing app.main pulls in # treats the page JS — slicing, not importing (importing app.main pulls in
# app.oidc → authlib, which the steward host does not have). # app.oidc → authlib, which the steward host does not have).
# #
# The guard reads the portal's guests ledger only: the member guest-request
# queue is GONE with the approval gate (removed 2026-11-08 — member
# invitations provision immediately, nothing is ever pending), so there is
# no "pending" branch to test and no payload carrying one.
#
# Run: python3 tests/test_guest_guard.py # Run: python3 tests/test_guest_guard.py
import re import re
import sys import sys
@@ -30,37 +35,38 @@ LEDGER_ACTIVE = [{"id": 3, "inviter": "info@inference.coop",
"recipient": "friend@example.com", "status": "active"}] "recipient": "friend@example.com", "status": "active"}]
LEDGER_LAPSED = [{"id": 3, "inviter": "info@inference.coop", LEDGER_LAPSED = [{"id": 3, "inviter": "info@inference.coop",
"recipient": "friend@example.com", "status": "expired"}] "recipient": "friend@example.com", "status": "expired"}]
PENDING_REQ = [{"id": 7, "inviter": "alice@example.com", EMPTY = {"ledger": []}
"recipient": "someone@example.com", "status": "pending"}]
EMPTY = {"ledger": [], "pending": []}
# An ACTIVE guest for the email → refuse, message names the email. # An ACTIVE guest for the email → refuse, message names the email.
refusal = guard({"ledger": LEDGER_ACTIVE, "pending": []}, "friend@example.com") refusal = guard({"ledger": LEDGER_ACTIVE}, "friend@example.com")
check("active guest refused", refusal is not None and refusal.startswith( check("active guest refused", refusal is not None and refusal.startswith(
"A guest account for friend@example.com already exists"), True) "A guest account for friend@example.com already exists"), True)
check("active refusal states no second account", check("active refusal states no second account",
"no second account" in (refusal or ""), True) "no second account" in (refusal or ""), True)
# Case/whitespace of the submitted email must not dodge the match. # Case/whitespace of the submitted email must not dodge the match.
check("case-insensitive match", guard({"ledger": LEDGER_ACTIVE, "pending": []}, check("case-insensitive match", guard({"ledger": LEDGER_ACTIVE},
" Friend@Example.COM ") is not None, True) " Friend@Example.COM ") is not None, True)
# A PENDING member request for the email → refuse as "awaits activation". # The guard no longer knows a "pending" state: a payload shaped like the old
refusal = guard({"ledger": [], "pending": PENDING_REQ}, "someone@example.com") # guest-requests response carries nothing the guard would act on.
check("pending request refused", refusal is not None and check("legacy pending-shaped payload is inert",
"awaits activation" in refusal and "someone@example.com" in refusal, True) guard({"ledger": [], "pending": [{"id": 7, "inviter": "alice@example.com",
"recipient": "someone@example.com",
"status": "pending"}]},
"someone@example.com"), None)
# Lapsed (expired/depleted) ledger row is NOT a live account: no panel-side # 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. # refusal — the portal's one-guest-per-recipient-ever guard is the authority.
check("expired ledger row falls through", check("expired ledger row falls through",
guard({"ledger": LEDGER_LAPSED, "pending": []}, "friend@example.com"), None) guard({"ledger": LEDGER_LAPSED}, "friend@example.com"), None)
# Someone else's guest/request never blocks a new address. # Someone else's guest never blocks a new address.
check("other recipients ignored", check("other recipients ignored",
guard({"ledger": LEDGER_ACTIVE, "pending": PENDING_REQ}, "new@example.com"), None) guard({"ledger": LEDGER_ACTIVE}, "new@example.com"), None)
# Empty/missing queues (portal unreadable → guard falls through, never blocks). # Empty/missing ledger (portal unreadable → guard falls through, never blocks).
check("empty queues pass", guard(EMPTY, "friend@example.com"), None) check("empty ledger passes", guard(EMPTY, "friend@example.com"), None)
check("missing keys pass", guard({}, "friend@example.com"), None) check("missing keys pass", guard({}, "friend@example.com"), None)
check("blank email passes (route validates first)", guard(EMPTY, ""), None) check("blank email passes (route validates first)", guard(EMPTY, ""), None)