From ca05b6d265a779cba570c3940c05fed8fd9b2459 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Thu, 30 Jul 2026 22:38:44 -0400 Subject: [PATCH 1/2] One admin search box: resolve an email or a principal id MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The admin surface accepted only exact principal ids because the host's IdentityPort — a deliberately narrow Pick — never listed the lookup. @pegma/identity has published findUserByEmail on its public Identity interface all along, so this needs no upstream change: widen the port and use it. - classifyLookup decides email vs principal id server-side on the one discriminator that is total here (Identity requires exactly one @ in every address; principal ids never contain one), so the operator gets a single box and the rule has one tested home. - POST /api/admin/lookup, not a GET with a query string: the query can be a real person's email, which then stays out of URLs, referrers, and logs, and CSRF plus same-origin gate the one endpoint that can confirm an address exists. Identity's public enumeration resistance is unchanged; this path needs an authenticated Admin holder. - New pegma.admin.principal.lookup limiter (120/h), swept with the rest, so a stolen admin session cannot harvest the directory. - The host never normalizes the email — it hands Identity the trimmed value, since exactly one normalization function exists and it lives there. Test-pinned. 208 node + 2 D1 tests green (6 new), tsc and astro check clean. Co-Authored-By: Claude Fable 5 --- docs/SUPPORT_COMPOSITION.md | 35 ++++++++ public/staff-roles.js | 79 ++++++++++++----- src/pages/staff/roles.astro | 12 +-- worker/src/admin-api.test.ts | 132 ++++++++++++++++++++++++++++- worker/src/admin-api.ts | 77 +++++++++++++++++ worker/src/identity-api.test.ts | 2 + worker/src/identity-contracts.ts | 1 + worker/src/index.ts | 6 ++ worker/src/support-api.test.ts | 6 ++ worker/src/support-desk.d1.test.ts | 1 + worker/src/support-desk.ts | 18 ++++ 11 files changed, 339 insertions(+), 30 deletions(-) diff --git a/docs/SUPPORT_COMPOSITION.md b/docs/SUPPORT_COMPOSITION.md index 5cfd842..de6ba63 100644 --- a/docs/SUPPORT_COMPOSITION.md +++ b/docs/SUPPORT_COMPOSITION.md @@ -146,10 +146,45 @@ with no default and styles the two modes differently. Mail / outbound notification is still deferred (Task 10) — staff reply omits `notification` like customer create/reply. +### Role administration (`/api/admin/…`) + +Gated on the stored `Admin` role (`@pegma/authorization-admin`); the host +checks permissions before calling the service, which never re-checks its own +callers. + +| Method | Path | Notes | +| --- | --- | --- | +| `GET` | `/api/admin/state` | `bootstrapArmed` + CSRF token | +| `POST` | `/api/admin/lookup` | One search box: body `{ query }`, resolves an email **or** a principal id | +| `GET` | `/api/admin/principals/:id` | Principal + active roles with `managedBy` | +| `GET` | `/api/admin/principals/:id/history` | Audited lifecycle timeline | +| `POST` | `/api/admin/principals/:id/roles` | Assign `Support` or `Admin` | +| `DELETE` | `/api/admin/assignments/:id` | Revoke; last-administrator guard | + +**One search box, decided server-side.** `classifyLookup` treats a `@` +anywhere in the query as an email and everything else as a principal id: +Identity's one normalization function requires exactly one `@` in every +address, and principal ids never contain one. Email lookups call the +published `Identity.findUserByEmail`; the host passes the trimmed value +through **without normalizing it**, because exactly one normalization +function exists and it lives in Identity (test-pinned). + +**Why the lookup is a POST.** The query can be a real person's email +address, so it stays out of URLs, referrers, and access logs; the same +choice puts CSRF and same-origin in front of the one endpoint that can +confirm an address exists. Identity's public enumeration resistance is +untouched — this path is reachable only by an authenticated `Admin` holder, +and it is rate-limited so a stolen admin session cannot harvest the +directory. + Durable rate-limit policies (separate from Identity): - `pegma.support.ticket.create` - `pegma.support.ticket.reply` (customer replies and staff message/note posts) +- `pegma.admin.role.mutate` (assign / revoke, 30/h per operator) +- `pegma.admin.principal.lookup` (directory lookups, 120/h per operator) + +All four are swept by the same scheduled maintenance run. ## Site pages diff --git a/public/staff-roles.js b/public/staff-roles.js index 968f9c7..308dc34 100644 --- a/public/staff-roles.js +++ b/public/staff-roles.js @@ -4,10 +4,11 @@ const forbidden = document.querySelector('#roles-forbidden'); const panel = document.querySelector('#roles-panel'); const bootstrapWarning = document.querySelector('#bootstrap-warning'); const lookupForm = document.querySelector('#lookup-form'); -const principalInput = document.querySelector('#lookup-principal'); +const lookupInput = document.querySelector('#lookup-query'); const principalCard = document.querySelector('#principal-card'); const principalEmail = document.querySelector('#principal-email'); const principalMeta = document.querySelector('#principal-meta'); +const principalMatched = document.querySelector('#principal-matched'); const roleList = document.querySelector('#role-list'); const assignForm = document.querySelector('#assign-form'); const assignRole = document.querySelector('#assign-role'); @@ -107,10 +108,11 @@ function renderRoles(roles) { ? 'Revoked — the guard restored the principal to keep an administrator.' : 'Revoked.', ); - await loadPrincipal(currentPrincipal); + await refreshPrincipal(); } catch (error) { showStatus( - MUTATION_ERRORS[error.message] ?? `Revoke failed (${error.message}).`, + MUTATION_ERRORS[error.message] ?? + `Revoke failed (${error.message}).`, true, ); } @@ -139,37 +141,68 @@ function renderHistory(events) { } } -async function loadPrincipal(principalId) { - const [detail, history] = await Promise.all([ - api(`/api/admin/principals/${encodeURIComponent(principalId)}`), - api(`/api/admin/principals/${encodeURIComponent(principalId)}/history`), - ]); - currentPrincipal = principalId; +function renderPrincipal(detail, matchedBy) { + currentPrincipal = detail.principal.principalId; principalEmail.textContent = detail.principal.email; principalMeta.textContent = `${detail.principal.principalId} · ${detail.principal.status} · created ${detail.principal.createdAt}`; + if (matchedBy === undefined) { + principalMatched.hidden = true; + } else { + principalMatched.textContent = + matchedBy === 'email' + ? 'Matched by email address.' + : 'Matched by principal id.'; + principalMatched.hidden = false; + } renderRoles(detail.roles); - renderHistory(history.events); principalCard.hidden = false; } +/** One box, one request: the worker decides email vs principal id. */ +async function resolvePrincipal(query) { + const detail = await api('/api/admin/lookup', { + method: 'POST', + body: JSON.stringify({ query }), + }); + renderPrincipal(detail, detail.matchedBy); + const id = encodeURIComponent(detail.principal.principalId); + const history = await api(`/api/admin/principals/${id}/history`); + renderHistory(history.events); +} + +/** Re-read the already-resolved principal after a mutation. */ +async function refreshPrincipal() { + const id = encodeURIComponent(currentPrincipal); + const [detail, history] = await Promise.all([ + api(`/api/admin/principals/${id}`), + api(`/api/admin/principals/${id}/history`), + ]); + renderPrincipal(detail); + renderHistory(history.events); +} + lookupForm.addEventListener('submit', async (event) => { event.preventDefault(); - const principalId = principalInput.value.trim(); - if (principalId === '') { + const query = lookupInput.value.trim(); + if (query === '') { return; } - showStatus('Loading principal…'); + showStatus('Looking up…'); try { - await loadPrincipal(principalId); + await resolvePrincipal(query); showStatus('Ready.'); } catch (error) { principalCard.hidden = true; - showStatus( - error.status === 404 - ? 'No account with that principal id.' - : `Lookup failed (${error.message}).`, - true, - ); + if (error.status === 404) { + showStatus('No account matches that email or principal id.', true); + } else if (error.status === 400) { + showStatus( + 'That does not look like an email address or a principal id.', + true, + ); + } else { + showStatus(`Lookup failed (${error.message}).`, true); + } } }); @@ -181,7 +214,9 @@ assignForm.addEventListener('submit', async (event) => { const role = assignRole.value; if ( role === 'Admin' && - !window.confirm('Grant the Admin role? Admins can change all role assignments.') + !window.confirm( + 'Grant the Admin role? Admins can change all role assignments.', + ) ) { return; } @@ -191,7 +226,7 @@ assignForm.addEventListener('submit', async (event) => { { method: 'POST', body: JSON.stringify({ role }) }, ); showStatus(`Assigned ${role}.`); - await loadPrincipal(currentPrincipal); + await refreshPrincipal(); } catch (error) { showStatus( MUTATION_ERRORS[error.message] ?? `Assign failed (${error.message}).`, diff --git a/src/pages/staff/roles.astro b/src/pages/staff/roles.astro index 62aa43a..e0e91d7 100644 --- a/src/pages/staff/roles.astro +++ b/src/pages/staff/roles.astro @@ -48,27 +48,27 @@ import Base from '../../layouts/Base.astro';