From 428cac14136553804181da59c30987e8f643d2ab Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 29 Jul 2026 11:06:24 -0400 Subject: [PATCH 1/4] Add Support Desk staff queue and ticket operator surface Allowlist staff via SUPPORT_STAFF_EMAILS / SUPPORT_STAFF_PRINCIPALS, expose /api/support/admin routes for queue/detail/reply/note/lifecycle, and ship authenticated /staff/support pages with explicit public vs internal compose. --- docs/SUPPORT_COMPOSITION.md | 90 +++++- public/staff-support-ticket.js | 301 +++++++++++++++++ public/staff-support.js | 152 +++++++++ src/pages/staff/support.astro | 83 +++++ src/pages/staff/support/ticket.astro | 125 ++++++++ src/styles/global.css | 91 +++++- worker/.dev.vars.example | 8 + worker/src/index.ts | 2 + worker/src/support-access.ts | 98 ++++++ worker/src/support-api.test.ts | 461 ++++++++++++++++++++++++++- worker/src/support-api.ts | 408 +++++++++++++++++++++++- worker/src/support-desk.ts | 10 + 12 files changed, 1815 insertions(+), 14 deletions(-) create mode 100644 public/staff-support-ticket.js create mode 100644 public/staff-support.js create mode 100644 src/pages/staff/support.astro create mode 100644 src/pages/staff/support/ticket.astro diff --git a/docs/SUPPORT_COMPOSITION.md b/docs/SUPPORT_COMPOSITION.md index 87e5edb..0612d58 100644 --- a/docs/SUPPORT_COMPOSITION.md +++ b/docs/SUPPORT_COMPOSITION.md @@ -2,7 +2,8 @@ Public host composition notes for authenticated product feedback on [pegma.dev](https://pegma.dev). This is the ecosystem's Cloudflare reference -environment for Support Desk customer create / list / read / reply. +environment for Support Desk customer create / list / read / reply and a small +staff operator surface over the same application services. ## Packages @@ -36,6 +37,8 @@ two never share a cursor key. ## Authorization +### Customer + Any authenticated pegma.dev account receives customer permissions through host AccessContext defaults (no paid entitlement): @@ -43,8 +46,34 @@ AccessContext defaults (no paid entitlement): - `support.ticket.read.own` - `support.ticket.reply.own` -`principalId` is the Identity principal / account id from the server-side -session (`__Host-pegma_session`). Browser-supplied identity fields are ignored. +Policy version: `pegma.dev-support-customer-1`. + +### Staff (host allowlist) + +Staff are **not** a full role store. Operators are allowlisted via env: + +| Env | Meaning | +| --- | --- | +| `SUPPORT_STAFF_EMAILS` | Comma-separated verified emails (case-insensitive) | +| `SUPPORT_STAFF_PRINCIPALS` | Comma-separated Identity principal / subject ids | + +A principal is staff only when authenticated **and** (principal id is in +`SUPPORT_STAFF_PRINCIPALS` **or** verified user email is in +`SUPPORT_STAFF_EMAILS`). Non-staff callers of staff routes receive **403** +`forbidden` (not 404). Unauthenticated callers receive **401**. + +Staff AccessContext policy version: `pegma.dev-support-staff-1`. Permissions: + +- `support.queue.read` +- `support.ticket.reply.any` +- `support.ticket.note` +- `support.ticket.assign` +- `support.ticket.manage` +- `support.audit.read` + +`principalId` is always the Identity principal / account id from the +server-side session (`__Host-pegma_session`). Browser-supplied identity fields +are ignored. ## Categories and markers @@ -56,7 +85,9 @@ Display marker: `[PEG-{number}]`. Public tracking URL: ## HTTP boundary -Worker routes (same-origin session + CSRF `X-Pegma-CSRF`): +Worker routes (same-origin session + CSRF `X-Pegma-CSRF` for mutations): + +### Customer | Method | Path | Notes | | --- | --- | --- | @@ -66,19 +97,56 @@ Worker routes (same-origin session + CSRF `X-Pegma-CSRF`): | `GET` | `/api/support/tickets/:id` | Read own; missing/non-owned → same 404 | | `POST` | `/api/support/tickets/:id/replies` | Reply (rate-limited) | +### Staff (`/api/support/admin/…`) + +| Method | Path | Notes | +| --- | --- | --- | +| `GET` | `/api/support/admin/queue` | `listStaffQueue`; query: `status`, `priority`, `sort` (`updated_newest` / `updated_oldest`), `unassignedOnly` | +| `GET` | `/api/support/admin/tickets/:id` | `readStaffTicket` (includes requester email when present, internal notes) | +| `POST` | `/api/support/admin/tickets/:id/messages` | Public staff reply → `replyAsStaff` body `{ body }` (rate-limited) | +| `POST` | `/api/support/admin/tickets/:id/notes` | Internal note → `addNote` body `{ body }` (rate-limited) | +| `PATCH` | `/api/support/admin/tickets/:id` | Lifecycle / assign / priority | + +`PATCH` body (strict keys): + +```json +{ + "action": "assign" | "unassign" | "change_priority" | "resolve" | "close" | "reopen", + "priority": "low" | "normal" | "high" | "urgent" +} +``` + +- `assign` assigns the caller's principal; `unassign` clears assignee. +- `change_priority` requires a valid `priority`. +- resolve / close / reopen map to the corresponding application methods. +- Command, correlation, and message IDs are server-minted. + +**Compose modes are distinct endpoints.** Public replies use `/messages`; +internal notes use `/notes`. The staff UI requires an explicit mode selection +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. + Durable rate-limit policies (separate from Identity): - `pegma.support.ticket.create` -- `pegma.support.ticket.reply` +- `pegma.support.ticket.reply` (customer replies and staff message/note posts) -Site pages: `/feedback` (create + list), `/feedback/ticket/?id=…` (read + reply; static shell). +## Site pages + +| URL | Audience | +| --- | --- | +| `/feedback` | Customer create + list | +| `/feedback/ticket/?id=…` | Customer read + reply | +| `/staff/support` | Staff queue (allowlisted operators) | +| `/staff/support/ticket/?id=…` | Staff ticket detail, compose, lifecycle | ## Maintenance and health Minute cron runs Support Desk queue repair and inactive projection sweep with independent cursors, plus Support Desk rate-limit sweeps. Mail send for support -notifications is deferred (templates are defined; create/reply omit -notification for this first host PR). +notifications is deferred (templates are defined; create/reply/staff reply omit +notification for this host surface). Health always reports Support Desk package detail without message content. A store probe runs only when `SUPPORT_HEALTH_PROBE` is exactly `"true"`. @@ -89,7 +157,11 @@ store probe runs only when `SUPPORT_HEALTH_PROBE` is exactly `"true"`. authorized operators. - Feedback is not automatically published to the roadmap, documentation, or GitHub Issues. -- Staff UI is deferred. +- The staff surface is only for allowlisted operators (env allowlist). It is + not a shared control plane with other hosts. +- Staff ticket views may include requester email after staff authz; customer + endpoints never gain staff fields. +- Internal notes must never appear on customer reads. - Queue projection terminal retention follows Support Desk's default (30 days) for inactive projection rows; authoritative ticket retention and export/redaction procedures remain host operational policy and will be diff --git a/public/staff-support-ticket.js b/public/staff-support-ticket.js new file mode 100644 index 0000000..91dbc1e --- /dev/null +++ b/public/staff-support-ticket.js @@ -0,0 +1,301 @@ +const statusNode = document.querySelector('#staff-ticket-status'); +const signedOut = document.querySelector('#staff-ticket-signed-out'); +const forbidden = document.querySelector('#staff-ticket-forbidden'); +const detail = document.querySelector('#staff-ticket-detail'); +const heading = document.querySelector('#staff-ticket-heading'); +const meta = document.querySelector('#staff-ticket-meta'); +const requesterNode = document.querySelector('#staff-ticket-requester'); +const messageList = document.querySelector('#staff-message-list'); +const composeForm = document.querySelector('#staff-compose-form'); +const composeBody = document.querySelector('#compose-body'); +const composeSubmit = document.querySelector('#compose-submit'); +const prioritySelect = document.querySelector('#priority-select'); +const ticketId = new URL(window.location.href).searchParams.get('id') ?? ''; + +let csrfToken = ''; +let currentView = null; + +function showStatus(message, isError = false) { + statusNode.textContent = message; + statusNode.dataset.tone = isError ? 'error' : 'neutral'; +} + +function hideAll() { + signedOut.hidden = true; + forbidden.hidden = true; + detail.hidden = true; +} + +async function api(path, init = {}) { + const headers = new Headers(init.headers); + if (init.body !== undefined) { + headers.set('Content-Type', 'application/json'); + } + if (csrfToken !== '') { + headers.set('X-Pegma-CSRF', csrfToken); + } + const response = await fetch(path, { + ...init, + headers, + credentials: 'same-origin', + }); + const body = await response.json(); + if (!response.ok) { + const error = new Error( + typeof body.error === 'string' ? body.error : 'request_failed', + ); + error.status = response.status; + throw error; + } + return body; +} + +function authorLabel(message) { + if (message.visibility === 'internal') { + return 'Internal note'; + } + if (message.authorKind === 'customer') { + return 'Customer'; + } + if (message.authorKind === 'staff') { + return 'Staff (public)'; + } + return 'System'; +} + +function renderMessages(messages) { + messageList.replaceChildren(); + for (const message of messages) { + const item = document.createElement('li'); + if (message.visibility === 'internal') { + item.className = 'staff-message-internal'; + } else if (message.authorKind === 'staff') { + item.className = 'staff-message-public-staff'; + } else if (message.authorKind === 'customer') { + item.className = 'staff-message-customer'; + } + + const who = document.createElement('strong'); + who.textContent = authorLabel(message); + const when = document.createElement('span'); + when.className = 'form-note'; + when.textContent = new Date(message.createdAt).toLocaleString(); + const body = document.createElement('p'); + body.textContent = message.body; + item.append(who, ' · ', when, body); + messageList.append(item); + } +} + +function renderTicket(view) { + currentView = view; + const marker = + typeof view.ticket.marker === 'string' + ? view.ticket.marker + : `[PEG-${view.ticket.number}]`; + heading.textContent = `${marker} ${view.ticket.subject}`; + meta.textContent = [ + view.ticket.status, + view.ticket.priority, + view.ticket.category ?? 'uncategorized', + view.ticket.channel, + `rev ${view.ticket.revision}`, + view.ticket.assignedTo + ? `assigned:${view.ticket.assignedTo}` + : 'unassigned', + ].join(' · '); + + const requester = view.ticket.requester ?? {}; + const requesterParts = [ + `association: ${requester.association ?? 'unknown'}`, + ]; + if (typeof requester.email === 'string') { + requesterParts.push(`email: ${requester.email}`); + } + if (typeof requester.principalId === 'string') { + requesterParts.push(`principal: ${requester.principalId}`); + } + requesterNode.textContent = requesterParts.join(' · '); + + if (prioritySelect) { + prioritySelect.value = view.ticket.priority; + } + + renderMessages(view.messages); + updateComposeEnabled(); +} + +function selectedComposeMode() { + const selected = composeForm.querySelector( + 'input[name="composeMode"]:checked', + ); + return selected ? selected.value : ''; +} + +function updateComposeEnabled() { + const mode = selectedComposeMode(); + const body = composeBody.value.trim(); + composeSubmit.disabled = mode === '' || body === ''; + composeForm.dataset.mode = mode === '' ? 'unset' : mode; +} + +async function patchTicket(action, extra = {}) { + showStatus(`Applying ${action}…`); + const view = await api( + `/api/support/admin/tickets/${encodeURIComponent(ticketId)}`, + { + method: 'PATCH', + body: JSON.stringify({ action, ...extra }), + }, + ); + if (typeof view.csrfToken === 'string') { + csrfToken = view.csrfToken; + } + renderTicket(view); + showStatus(`Action ${action} applied.`); +} + +async function loadTicket() { + if (ticketId === '') { + showStatus('Missing ticket id.', true); + return; + } + const idDisplay = document.querySelector('#staff-ticket-id-display'); + if (idDisplay) idDisplay.textContent = ticketId; + + hideAll(); + try { + await api('/api/identity/account'); + } catch (error) { + if (error.status === 401) { + signedOut.hidden = false; + showStatus('Sign in to view this ticket.'); + return; + } + showStatus(`Staff ticket unavailable: ${error.message}`, true); + return; + } + + try { + const view = await api( + `/api/support/admin/tickets/${encodeURIComponent(ticketId)}`, + ); + if (typeof view.csrfToken === 'string') { + csrfToken = view.csrfToken; + } + detail.hidden = false; + renderTicket(view); + showStatus('Ticket loaded.'); + } catch (error) { + if (error.status === 401) { + signedOut.hidden = false; + showStatus('Sign in to view this ticket.'); + return; + } + if (error.status === 403) { + forbidden.hidden = false; + showStatus('You do not have staff access.', true); + return; + } + if (error.status === 404) { + showStatus('Ticket not found.', true); + return; + } + showStatus(`Could not load ticket: ${error.message}`, true); + } +} + +function bindLifecycle() { + document + .querySelector('#action-assign') + ?.addEventListener('click', async () => { + try { + await patchTicket('assign'); + } catch (error) { + showStatus(`Assign failed: ${error.message}`, true); + } + }); + document + .querySelector('#action-unassign') + ?.addEventListener('click', async () => { + try { + await patchTicket('unassign'); + } catch (error) { + showStatus(`Unassign failed: ${error.message}`, true); + } + }); + document + .querySelector('#action-priority') + ?.addEventListener('click', async () => { + try { + await patchTicket('change_priority', { + priority: prioritySelect.value, + }); + } catch (error) { + showStatus(`Priority change failed: ${error.message}`, true); + } + }); + document + .querySelector('#action-resolve') + ?.addEventListener('click', async () => { + try { + await patchTicket('resolve'); + } catch (error) { + showStatus(`Resolve failed: ${error.message}`, true); + } + }); + document + .querySelector('#action-close') + ?.addEventListener('click', async () => { + try { + await patchTicket('close'); + } catch (error) { + showStatus(`Close failed: ${error.message}`, true); + } + }); + document + .querySelector('#action-reopen') + ?.addEventListener('click', async () => { + try { + await patchTicket('reopen'); + } catch (error) { + showStatus(`Reopen failed: ${error.message}`, true); + } + }); +} + +composeForm.addEventListener('change', updateComposeEnabled); +composeForm.addEventListener('input', updateComposeEnabled); + +composeForm.addEventListener('submit', async (event) => { + event.preventDefault(); + const mode = selectedComposeMode(); + const body = composeBody.value.trim(); + if (mode === '' || body === '') { + showStatus('Select Public reply or Internal note, and enter a body.', true); + return; + } + + const path = + mode === 'public' + ? `/api/support/admin/tickets/${encodeURIComponent(ticketId)}/messages` + : `/api/support/admin/tickets/${encodeURIComponent(ticketId)}/notes`; + + try { + showStatus(mode === 'public' ? 'Sending public reply…' : 'Saving note…'); + const view = await api(path, { + method: 'POST', + body: JSON.stringify({ body }), + }); + composeForm.reset(); + updateComposeEnabled(); + renderTicket(view); + showStatus(mode === 'public' ? 'Public reply sent.' : 'Internal note saved.'); + } catch (error) { + showStatus(`Compose failed: ${error.message}`, true); + } +}); + +bindLifecycle(); +updateComposeEnabled(); +loadTicket(); diff --git a/public/staff-support.js b/public/staff-support.js new file mode 100644 index 0000000..0d8a2e5 --- /dev/null +++ b/public/staff-support.js @@ -0,0 +1,152 @@ +const statusNode = document.querySelector('#staff-queue-status'); +const signedOut = document.querySelector('#staff-queue-signed-out'); +const forbidden = document.querySelector('#staff-queue-forbidden'); +const panel = document.querySelector('#staff-queue-panel'); +const emailNode = document.querySelector('#staff-queue-email'); +const queueList = document.querySelector('#queue-list'); +const filterForm = document.querySelector('#queue-filters'); + +let csrfToken = ''; + +function showStatus(message, isError = false) { + statusNode.textContent = message; + statusNode.dataset.tone = isError ? 'error' : 'neutral'; +} + +function hideAll() { + signedOut.hidden = true; + forbidden.hidden = true; + panel.hidden = true; +} + +async function api(path, init = {}) { + const headers = new Headers(init.headers); + if (init.body !== undefined) { + headers.set('Content-Type', 'application/json'); + } + if (csrfToken !== '') { + headers.set('X-Pegma-CSRF', csrfToken); + } + const response = await fetch(path, { + ...init, + headers, + credentials: 'same-origin', + }); + const body = await response.json(); + if (!response.ok) { + const error = new Error( + typeof body.error === 'string' ? body.error : 'request_failed', + ); + error.status = response.status; + throw error; + } + return body; +} + +function renderQueue(items) { + queueList.replaceChildren(); + if (items.length === 0) { + const empty = document.createElement('li'); + empty.textContent = 'No tickets match these filters.'; + queueList.append(empty); + return; + } + for (const item of items) { + const li = document.createElement('li'); + const link = document.createElement('a'); + link.href = `/staff/support/ticket/?id=${encodeURIComponent(item.ticketId)}`; + link.textContent = item.ticketId; + const meta = document.createElement('span'); + meta.className = 'form-note'; + const parts = [ + item.status, + item.priority, + item.category ?? 'uncategorized', + item.requesterAssociation, + item.assignedTo ? `assigned:${item.assignedTo}` : 'unassigned', + new Date(item.updatedAt).toLocaleString(), + ]; + meta.textContent = parts.join(' · '); + li.append(link, meta); + queueList.append(li); + } +} + +function filterQuery() { + const form = new FormData(filterForm); + const params = new URLSearchParams(); + const status = form.get('status'); + const sort = form.get('sort'); + if (typeof status === 'string' && status !== '') { + params.set('status', status); + } + if (typeof sort === 'string' && sort !== '') { + params.set('sort', sort); + } + const query = params.toString(); + return query === '' + ? '/api/support/admin/queue' + : `/api/support/admin/queue?${query}`; +} + +async function refreshQueue() { + const result = await api(filterQuery()); + if (typeof result.csrfToken === 'string') { + csrfToken = result.csrfToken; + } + renderQueue(result.items); +} + +async function start() { + hideAll(); + try { + const account = await api('/api/identity/account'); + csrfToken = account.csrfToken; + emailNode.textContent = account.account.email; + } catch (error) { + if (error.status === 401) { + signedOut.hidden = false; + showStatus('Sign in to use the staff queue.'); + return; + } + showStatus(`Staff queue unavailable: ${error.message}`, true); + return; + } + + try { + await refreshQueue(); + panel.hidden = false; + showStatus('Queue loaded.'); + } catch (error) { + if (error.status === 401) { + signedOut.hidden = false; + showStatus('Sign in to use the staff queue.'); + return; + } + if (error.status === 403) { + forbidden.hidden = false; + showStatus('You do not have staff access.', true); + return; + } + showStatus(`Could not load queue: ${error.message}`, true); + } +} + +filterForm.addEventListener('submit', async (event) => { + event.preventDefault(); + try { + showStatus('Refreshing queue…'); + await refreshQueue(); + showStatus('Queue updated.'); + } catch (error) { + if (error.status === 403) { + hideAll(); + forbidden.hidden = false; + showStatus('You do not have staff access.', true); + return; + } + showStatus(`Could not load queue: ${error.message}`, true); + } +}); + +start(); diff --git a/src/pages/staff/support.astro b/src/pages/staff/support.astro new file mode 100644 index 0000000..5ec40a9 --- /dev/null +++ b/src/pages/staff/support.astro @@ -0,0 +1,83 @@ +--- +import Base from '../../layouts/Base.astro'; +--- + + +
+

Staff · Support Desk

+

Support queue

+

+ Review and act on product feedback tickets. Access is limited to operators + listed in the host staff allowlist — this is not a public control plane. +

+
+ +
+ Checking staff access… +
+ + + + + + + + + + + diff --git a/src/pages/staff/support/ticket.astro b/src/pages/staff/support/ticket.astro new file mode 100644 index 0000000..1bd2b87 --- /dev/null +++ b/src/pages/staff/support/ticket.astro @@ -0,0 +1,125 @@ +--- +import Base from '../../../layouts/Base.astro'; +--- + + +
+

Staff · Ticket

+

Loading…

+

+ Operator conversation for ticket + …. Public replies and internal + notes use separate endpoints and must never be confused. +

+
+ +
+ Loading ticket… +
+ + + + + + + + + diff --git a/src/styles/global.css b/src/styles/global.css index 8d589e3..6ecd87e 100644 --- a/src/styles/global.css +++ b/src/styles/global.css @@ -437,10 +437,99 @@ h2 { } #feedback-status[data-tone="error"], -#ticket-status[data-tone="error"] { +#ticket-status[data-tone="error"], +#staff-queue-status[data-tone="error"], +#staff-ticket-status[data-tone="error"] { border-left-color: #a33; } +/* Staff support surfaces */ + +.staff-queue-filters { + margin-bottom: 1rem; +} + +.staff-lifecycle { + display: flex; + flex-direction: column; + gap: 1rem; + margin-bottom: 1.5rem; +} + +.staff-lifecycle-row { + flex-wrap: wrap; + justify-content: flex-start; +} + +.staff-priority-form { + margin-top: 0; + max-width: 18rem; +} + +.staff-compose-mode { + margin: 0 0 1rem; + padding: 0.85rem; + border: 1px solid var(--line); + border-radius: 0.5rem; +} + +.staff-compose-mode legend { + padding: 0 0.35rem; + font-size: 0.9rem; + font-weight: 650; +} + +.staff-mode-option { + display: flex; + gap: 0.65rem; + align-items: flex-start; + margin: 0.55rem 0; + padding: 0.65rem 0.75rem; + border: 1px solid var(--line); + border-radius: 0.45rem; + cursor: pointer; +} + +.staff-mode-option input { + margin-top: 0.2rem; + flex: 0 0 auto; + width: auto; +} + +.staff-mode-public { + background: var(--paper); +} + +.staff-mode-internal { + border-color: #c4922a; + background: color-mix(in srgb, #c4922a 12%, var(--paper)); +} + +.staff-compose[data-mode="public"] #compose-body { + border-color: var(--ink); +} + +.staff-compose[data-mode="internal"] #compose-body { + border-color: #c4922a; + background: color-mix(in srgb, #c4922a 8%, var(--paper)); +} + +.staff-message-internal { + border-left: 3px solid #c4922a; + padding-left: 0.75rem; + background: color-mix(in srgb, #c4922a 10%, transparent); +} + +.staff-message-public-staff { + border-left: 3px solid var(--ink); + padding-left: 0.75rem; +} + +.staff-message-customer { + border-left: 3px solid var(--slate); + padding-left: 0.75rem; +} + button { padding: 0.65rem 0.9rem; border: 1px solid var(--ink); diff --git a/worker/.dev.vars.example b/worker/.dev.vars.example index bb1c3aa..701e94d 100644 --- a/worker/.dev.vars.example +++ b/worker/.dev.vars.example @@ -4,3 +4,11 @@ # IDENTITY_EMAIL_CODE_SECRET_BASE64= # RESEND_API_KEY= # GITHUB_WEBHOOK_SECRET= + +# Support Desk staff allowlist (comma-separated). A principal is staff when +# authenticated and (principal id is listed OR verified email is listed). +# SUPPORT_STAFF_EMAILS=ops@example.test,other@example.test +# SUPPORT_STAFF_PRINCIPALS=principal-id-1,principal-id-2 + +# Optional: set to "true" to probe Support Desk storage from /health. +# SUPPORT_HEALTH_PROBE=true diff --git a/worker/src/index.ts b/worker/src/index.ts index e2cf284..81035b2 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -24,6 +24,7 @@ import { } from './release-reconciliation'; import { handleGetReleases, readReleasesConfig } from './releases-api'; import { createSupportApi } from './support-api'; +import { parseStaffAllowlist } from './support-access'; import { createProductionSupportRuntime, probeSupportStore, @@ -54,6 +55,7 @@ function createSupportHandler(env: AppEnv, logger: ReturnType; + /** Identity principal / subject ids. */ + readonly principals: ReadonlySet; +} + +const EMPTY_STAFF_ALLOWLIST: StaffAllowlist = Object.freeze({ + emails: Object.freeze(new Set()), + principals: Object.freeze(new Set()), +}); + +function parseCommaList(value: string | undefined): string[] { + if (value === undefined || value.trim() === '') { + return []; + } + return value + .split(',') + .map((part) => part.trim()) + .filter((part) => part.length > 0); +} + +/** + * Parse `SUPPORT_STAFF_EMAILS` and `SUPPORT_STAFF_PRINCIPALS` from host env. + * + * Emails are lowercased for case-insensitive comparison. Principal ids are + * kept as-is (trimmed). Empty or missing env → empty allowlist (no staff). + */ +export function parseStaffAllowlist(env: { + readonly SUPPORT_STAFF_EMAILS?: string; + readonly SUPPORT_STAFF_PRINCIPALS?: string; +}): StaffAllowlist { + const emails = new Set( + parseCommaList(env.SUPPORT_STAFF_EMAILS).map((email) => + email.toLowerCase(), + ), + ); + const principals = new Set(parseCommaList(env.SUPPORT_STAFF_PRINCIPALS)); + return Object.freeze({ + emails: Object.freeze(emails), + principals: Object.freeze(principals), + }); +} + +/** Empty allowlist for hosts/tests that inject staff later. */ +export function emptyStaffAllowlist(): StaffAllowlist { + return EMPTY_STAFF_ALLOWLIST; +} + /** * Resolve an AccessContext for an authenticated Identity principal. * @@ -35,3 +103,33 @@ export function customerAccessContext( }, ); } + +/** + * Resolve staff AccessContext when the principal is on the host allowlist. + * + * A principal is staff only when authenticated **and** (principal id is in + * `SUPPORT_STAFF_PRINCIPALS` **or** verified user email is in + * `SUPPORT_STAFF_EMAILS`). Returns `null` when not staff — callers map that + * to HTTP 403 `forbidden` (not 404). + */ +export function staffAccessContext( + principalId: PrincipalId, + allowlist: StaffAllowlist, + userEmail?: string, +): AccessContext | null { + const principalAllowed = allowlist.principals.has(principalId); + const emailAllowed = + userEmail !== undefined && + userEmail.trim() !== '' && + allowlist.emails.has(userEmail.trim().toLowerCase()); + if (!principalAllowed && !emailAllowed) { + return null; + } + return resolveAccess( + { principalId }, + { + version: SUPPORT_STAFF_POLICY_VERSION, + defaults: [...SUPPORT_STAFF_PERMISSIONS], + }, + ); +} diff --git a/worker/src/support-api.test.ts b/worker/src/support-api.test.ts index fdb5fb9..ccdf4c6 100644 --- a/worker/src/support-api.test.ts +++ b/worker/src/support-api.test.ts @@ -17,7 +17,13 @@ import type { VerifiedIdentityClaims, } from './identity-contracts'; import { createSupportApi } from './support-api'; -import { customerAccessContext } from './support-access'; +import { + customerAccessContext, + parseStaffAllowlist, + staffAccessContext, + SUPPORT_STAFF_PERMISSIONS, + SUPPORT_STAFF_POLICY_VERSION, +} from './support-access'; import { createSupportRuntime, formatPegmaTicketSubject, @@ -33,6 +39,7 @@ import { runSupportMaintenance } from './support-maintenance'; const principalA = 'principal-a' as PrincipalId; const principalB = 'principal-b' as PrincipalId; +const principalStaff = 'principal-staff' as PrincipalId; const clock = fixedClock('2026-07-29T12:00:00.000Z'); const logger: Logger = { log: vi.fn() }; @@ -119,12 +126,33 @@ function post( }); } -function fixture() { +function patch( + path: string, + body: unknown, + headers: Record = {}, +): Request { + return new Request(`https://pegma.dev${path}`, { + method: 'PATCH', + headers: { + 'Content-Type': 'application/json', + Origin: IDENTITY_ISSUER, + 'Sec-Fetch-Site': 'same-origin', + ...headers, + }, + body: JSON.stringify(body), + }); +} + +function fixture(options: { + readonly staffPrincipals?: readonly PrincipalId[]; + readonly staffEmails?: readonly string[]; +} = {}) { const store = createMemoryStore(); const sessions = createSessionStore(store, { logger }); const users = new Map([ [principalA, userFor(principalA, 'a@example.test')], [principalB, userFor(principalB, 'b@example.test')], + [principalStaff, userFor(principalStaff, 'staff@example.test')], ]); const identity = identityFor(users); const runtime = createSupportRuntime({ @@ -135,6 +163,10 @@ function fixture() { logger, clock, }); + const staffAllowlist = parseStaffAllowlist({ + SUPPORT_STAFF_PRINCIPALS: (options.staffPrincipals ?? []).join(','), + SUPPORT_STAFF_EMAILS: (options.staffEmails ?? []).join(','), + }); const api = createSupportApi({ application: runtime.application, sessions, @@ -143,10 +175,49 @@ function fixture() { createLimiter: runtime.createLimiter, replyLimiter: runtime.replyLimiter, logger, + staffAllowlist, }); return { store, sessions, runtime, api, application: runtime.application }; } +async function createCustomerTicket( + api: ReturnType, + sessions: ReturnType, + principalId: PrincipalId, + csrfChar = 'c', +): Promise<{ + cookie: string; + csrfToken: string; + ticketId: string; + ticketNumber: number; +}> { + const auth = await sessionCookie(sessions, principalId, csrfChar.repeat(43)); + const created = await api( + post( + '/api/support/tickets', + { + subject: 'Roadmap clarity', + body: 'The roadmap page is hard to scan.', + category: 'feedback', + }, + { + Cookie: auth.cookie, + 'X-Pegma-CSRF': auth.csrfToken, + }, + ), + ); + expect(created.status).toBe(201); + const body = (await created.json()) as { + ticket: { id: string; number: number }; + }; + return { + cookie: auth.cookie, + csrfToken: auth.csrfToken, + ticketId: body.ticket.id, + ticketNumber: body.ticket.number, + }; +} + describe('support subject markers and URLs', () => { it('formats [PEG-…] markers and public ticket URLs', () => { expect(pegSubjectMarker(1042)).toBe('[PEG-1042]'); @@ -443,3 +514,389 @@ describe('application ownership boundary', () => { ).rejects.toBeInstanceOf(SupportDeskNotFoundError); }); }); + +describe('staff allowlist and access', () => { + it('parses env allowlists case-insensitively for emails', () => { + const allowlist = parseStaffAllowlist({ + SUPPORT_STAFF_EMAILS: ' Ops@Example.TEST , other@example.test ', + SUPPORT_STAFF_PRINCIPALS: ' principal-staff , principal-x ', + }); + expect(allowlist.emails.has('ops@example.test')).toBe(true); + expect(allowlist.emails.has('other@example.test')).toBe(true); + expect(allowlist.principals.has('principal-staff')).toBe(true); + expect(allowlist.principals.has('principal-x')).toBe(true); + }); + + it('grants staff permissions only for allowlisted principals or emails', () => { + const byPrincipal = parseStaffAllowlist({ + SUPPORT_STAFF_PRINCIPALS: principalStaff, + }); + const byEmail = parseStaffAllowlist({ + SUPPORT_STAFF_EMAILS: 'staff@example.test', + }); + const empty = parseStaffAllowlist({}); + + const staffByPrincipal = staffAccessContext( + principalStaff, + byPrincipal, + 'staff@example.test', + ); + expect(staffByPrincipal).not.toBeNull(); + expect(staffByPrincipal?.policyVersion).toBe(SUPPORT_STAFF_POLICY_VERSION); + expect(staffByPrincipal?.permissions).toEqual( + expect.arrayContaining([...SUPPORT_STAFF_PERMISSIONS]), + ); + + const staffByEmail = staffAccessContext( + principalA, + byEmail, + 'STAFF@example.test', + ); + expect(staffByEmail).not.toBeNull(); + + expect(staffAccessContext(principalA, empty, 'a@example.test')).toBeNull(); + expect( + staffAccessContext(principalA, byPrincipal, 'a@example.test'), + ).toBeNull(); + }); +}); + +describe('staff support API', () => { + it('returns 401 for unauthenticated staff routes', async () => { + const { api } = fixture({ staffPrincipals: [principalStaff] }); + const queue = await api(get('/api/support/admin/queue')); + expect(queue.status).toBe(401); + expect(await queue.json()).toEqual({ error: 'authentication_required' }); + + const ticket = await api(get('/api/support/admin/tickets/any-id')); + expect(ticket.status).toBe(401); + }); + + it('returns 403 for authenticated non-staff on queue, read, reply, and note', async () => { + const { api, sessions } = fixture({ staffPrincipals: [principalStaff] }); + const customer = await createCustomerTicket(api, sessions, principalA, 'a'); + const nonStaff = await sessionCookie(sessions, principalB, 'b'.repeat(43)); + + const queue = await api(get('/api/support/admin/queue', nonStaff.cookie)); + expect(queue.status).toBe(403); + expect(await queue.json()).toEqual({ error: 'forbidden' }); + + const read = await api( + get( + `/api/support/admin/tickets/${customer.ticketId}`, + nonStaff.cookie, + ), + ); + expect(read.status).toBe(403); + expect(await read.json()).toEqual({ error: 'forbidden' }); + + const reply = await api( + post( + `/api/support/admin/tickets/${customer.ticketId}/messages`, + { body: 'Should fail.' }, + { + Cookie: nonStaff.cookie, + 'X-Pegma-CSRF': nonStaff.csrfToken, + }, + ), + ); + expect(reply.status).toBe(403); + expect(await reply.json()).toEqual({ error: 'forbidden' }); + + const note = await api( + post( + `/api/support/admin/tickets/${customer.ticketId}/notes`, + { body: 'Internal should fail.' }, + { + Cookie: nonStaff.cookie, + 'X-Pegma-CSRF': nonStaff.csrfToken, + }, + ), + ); + expect(note.status).toBe(403); + expect(await note.json()).toEqual({ error: 'forbidden' }); + }); + + it('lists the queue for allowlisted staff after customer create', async () => { + const { api, sessions } = fixture({ staffPrincipals: [principalStaff] }); + const customer = await createCustomerTicket(api, sessions, principalA, 'a'); + const staff = await sessionCookie( + sessions, + principalStaff, + 's'.repeat(43), + ); + + const queue = await api(get('/api/support/admin/queue', staff.cookie)); + expect(queue.status).toBe(200); + const body = (await queue.json()) as { + items: readonly { ticketId: string; status: string }[]; + csrfToken: string; + }; + expect(body.items.some((item) => item.ticketId === customer.ticketId)).toBe( + true, + ); + expect(typeof body.csrfToken).toBe('string'); + }); + + it('reads staff ticket including messages and requester email', async () => { + const { api, sessions } = fixture({ staffPrincipals: [principalStaff] }); + const customer = await createCustomerTicket(api, sessions, principalA, 'a'); + const staff = await sessionCookie( + sessions, + principalStaff, + 's'.repeat(43), + ); + + const read = await api( + get( + `/api/support/admin/tickets/${customer.ticketId}`, + staff.cookie, + ), + ); + expect(read.status).toBe(200); + const body = (await read.json()) as { + ticket: { + id: string; + number: number; + subject: string; + requester: { email?: string; association: string }; + }; + messages: readonly { body: string; authorKind: string }[]; + }; + expect(body.ticket.id).toBe(customer.ticketId); + expect(body.ticket.number).toBe(customer.ticketNumber); + expect(body.ticket.subject).toBe('Roadmap clarity'); + expect(body.ticket.requester.email).toBe('a@example.test'); + expect(body.messages).toHaveLength(1); + expect(body.messages[0]?.authorKind).toBe('customer'); + }); + + it('public staff reply is customer-visible and advances status', async () => { + const { api, sessions } = fixture({ staffPrincipals: [principalStaff] }); + const customer = await createCustomerTicket(api, sessions, principalA, 'a'); + const staff = await sessionCookie( + sessions, + principalStaff, + 's'.repeat(43), + ); + + const replied = await api( + post( + `/api/support/admin/tickets/${customer.ticketId}/messages`, + { body: 'Thanks — we will clarify the roadmap sections.' }, + { + Cookie: staff.cookie, + 'X-Pegma-CSRF': staff.csrfToken, + }, + ), + ); + expect(replied.status).toBe(201); + const staffView = (await replied.json()) as { + ticket: { status: string }; + messages: readonly { + body: string; + authorKind: string; + visibility: string; + }[]; + }; + expect(staffView.ticket.status).toBe('waiting_on_customer'); + const publicStaff = staffView.messages.find( + (m) => m.authorKind === 'staff' && m.visibility === 'customer', + ); + expect(publicStaff?.body).toContain('clarify the roadmap'); + + const customerRead = await api( + get(`/api/support/tickets/${customer.ticketId}`, customer.cookie), + ); + expect(customerRead.status).toBe(200); + const customerView = (await customerRead.json()) as { + ticket: { status: string }; + messages: readonly { body: string; authorKind: string }[]; + }; + expect(customerView.ticket.status).toBe('waiting_on_customer'); + expect( + customerView.messages.some((m) => + m.body.includes('clarify the roadmap'), + ), + ).toBe(true); + }); + + it('internal notes are staff-only and never on customer read', async () => { + const { api, sessions } = fixture({ staffPrincipals: [principalStaff] }); + const customer = await createCustomerTicket(api, sessions, principalA, 'a'); + const staff = await sessionCookie( + sessions, + principalStaff, + 's'.repeat(43), + ); + + const noted = await api( + post( + `/api/support/admin/tickets/${customer.ticketId}/notes`, + { body: 'Internal: check docs PR #42 before replying.' }, + { + Cookie: staff.cookie, + 'X-Pegma-CSRF': staff.csrfToken, + }, + ), + ); + expect(noted.status).toBe(201); + const staffView = (await noted.json()) as { + messages: readonly { + body: string; + visibility: string; + authorKind: string; + }[]; + }; + const internal = staffView.messages.find( + (m) => m.visibility === 'internal', + ); + expect(internal?.body).toContain('docs PR #42'); + expect(internal?.authorKind).toBe('staff'); + + const customerRead = await api( + get(`/api/support/tickets/${customer.ticketId}`, customer.cookie), + ); + expect(customerRead.status).toBe(200); + const customerView = (await customerRead.json()) as { + messages: readonly { body: string; visibility: string }[]; + }; + expect( + customerView.messages.some((m) => m.body.includes('docs PR #42')), + ).toBe(false); + expect( + customerView.messages.every((m) => m.visibility === 'customer'), + ).toBe(true); + }); + + it('keeps public reply and internal note on separate endpoints', async () => { + const { api, sessions } = fixture({ staffPrincipals: [principalStaff] }); + const customer = await createCustomerTicket(api, sessions, principalA, 'a'); + const staff = await sessionCookie( + sessions, + principalStaff, + 's'.repeat(43), + ); + + const viaMessages = await api( + post( + `/api/support/admin/tickets/${customer.ticketId}/messages`, + { body: 'Public only path.' }, + { + Cookie: staff.cookie, + 'X-Pegma-CSRF': staff.csrfToken, + }, + ), + ); + expect(viaMessages.status).toBe(201); + const publicView = (await viaMessages.json()) as { + messages: readonly { body: string; visibility: string }[]; + }; + expect( + publicView.messages.some( + (m) => + m.body === 'Public only path.' && m.visibility === 'customer', + ), + ).toBe(true); + + const viaNotes = await api( + post( + `/api/support/admin/tickets/${customer.ticketId}/notes`, + { body: 'Note only path.' }, + { + Cookie: staff.cookie, + 'X-Pegma-CSRF': staff.csrfToken, + }, + ), + ); + expect(viaNotes.status).toBe(201); + const noteView = (await viaNotes.json()) as { + messages: readonly { body: string; visibility: string }[]; + }; + expect( + noteView.messages.some( + (m) => m.body === 'Note only path.' && m.visibility === 'internal', + ), + ).toBe(true); + + // Wrong resource path stays not_found (does not silently create notes). + const wrong = await api( + post( + `/api/support/admin/tickets/${customer.ticketId}/replies`, + { body: 'Wrong path.' }, + { + Cookie: staff.cookie, + 'X-Pegma-CSRF': staff.csrfToken, + }, + ), + ); + expect(wrong.status).toBe(404); + }); + + it('supports assign, priority change, and resolve for staff', async () => { + const { api, sessions } = fixture({ staffPrincipals: [principalStaff] }); + const customer = await createCustomerTicket(api, sessions, principalA, 'a'); + const staff = await sessionCookie( + sessions, + principalStaff, + 's'.repeat(43), + ); + const headers = { + Cookie: staff.cookie, + 'X-Pegma-CSRF': staff.csrfToken, + }; + + const assigned = await api( + patch( + `/api/support/admin/tickets/${customer.ticketId}`, + { action: 'assign' }, + headers, + ), + ); + expect(assigned.status).toBe(200); + const assignedBody = (await assigned.json()) as { + ticket: { assignedTo?: string; priority: string; status: string }; + }; + expect(assignedBody.ticket.assignedTo).toBe(principalStaff); + + const priority = await api( + patch( + `/api/support/admin/tickets/${customer.ticketId}`, + { action: 'change_priority', priority: 'high' }, + headers, + ), + ); + expect(priority.status).toBe(200); + const priorityBody = (await priority.json()) as { + ticket: { priority: string }; + }; + expect(priorityBody.ticket.priority).toBe('high'); + + const resolved = await api( + patch( + `/api/support/admin/tickets/${customer.ticketId}`, + { action: 'resolve' }, + headers, + ), + ); + expect(resolved.status).toBe(200); + const resolvedBody = (await resolved.json()) as { + ticket: { status: string }; + }; + expect(resolvedBody.ticket.status).toBe('resolved'); + }); + + it('allows staff by verified email allowlist', async () => { + const { api, sessions } = fixture({ + staffEmails: ['staff@example.test'], + }); + await createCustomerTicket(api, sessions, principalA, 'a'); + const staff = await sessionCookie( + sessions, + principalStaff, + 's'.repeat(43), + ); + const queue = await api(get('/api/support/admin/queue', staff.cookie)); + expect(queue.status).toBe(200); + }); +}); diff --git a/worker/src/support-api.ts b/worker/src/support-api.ts index 5d76fd7..04284e9 100644 --- a/worker/src/support-api.ts +++ b/worker/src/support-api.ts @@ -4,8 +4,17 @@ import type { DurableRateLimiter } from '@pegma/rate-limit'; import type { CustomerTicketSummary, CustomerTicketView, + StaffQueueItem, + StaffQueueQuery, + StaffTicketView, SupportDeskApplication, } from '@pegma/support-desk-application'; +import type { + Ticket, + TicketMessage, + TicketPriority, + TicketStatus, +} from '@pegma/support-desk-contracts'; import { IDENTITY_ISSUER, SESSION_COOKIE, @@ -17,7 +26,12 @@ import type { IdentityUser, VerifiedIdentityClaims, } from './identity-contracts'; -import { customerAccessContext } from './support-access'; +import { + customerAccessContext, + emptyStaffAllowlist, + staffAccessContext, + type StaffAllowlist, +} from './support-access'; import { mapSupportError, mintSupportId, @@ -38,6 +52,40 @@ const SESSION_DATA_KEYS = new Set([ ]); const TICKET_ID_PATH = /^\/api\/support\/tickets\/([A-Za-z0-9._~-]{1,200})(?:\/(replies))?$/u; +const ADMIN_TICKET_PATH = + /^\/api\/support\/admin\/tickets\/([A-Za-z0-9._~-]{1,200})(?:\/(messages|notes))?$/u; + +const TICKET_STATUSES = new Set([ + 'open', + 'waiting_on_support', + 'waiting_on_customer', + 'resolved', + 'closed', +]); +const TICKET_PRIORITIES = new Set([ + 'low', + 'normal', + 'high', + 'urgent', +]); +const QUEUE_SORTS = new Set(['updated_newest', 'updated_oldest'] as const); +const STAFF_PATCH_ACTIONS = new Set([ + 'assign', + 'unassign', + 'change_priority', + 'resolve', + 'close', + 'reopen', +] as const); + +type QueueSort = 'updated_newest' | 'updated_oldest'; +type StaffPatchAction = + | 'assign' + | 'unassign' + | 'change_priority' + | 'resolve' + | 'close' + | 'reopen'; interface SupportApiOptions { readonly application: SupportDeskApplication; @@ -47,6 +95,11 @@ interface SupportApiOptions { readonly createLimiter: DurableRateLimiter; readonly replyLimiter: DurableRateLimiter; readonly logger: Logger; + /** + * Host staff allowlist. Prefer injecting from env via `parseStaffAllowlist` + * so tests can supply a fixed list without process env. + */ + readonly staffAllowlist?: StaffAllowlist; } interface SessionData { @@ -437,6 +490,74 @@ function publicTicketView(view: CustomerTicketView) { }; } +/** Staff-safe ticket fields for operator surfaces (includes requester email). */ +function staffTicketDto(ticket: Ticket) { + return { + id: ticket.id, + number: ticket.number, + subject: ticket.subject, + ...(ticket.category === undefined ? {} : { category: ticket.category }), + status: ticket.status, + priority: ticket.priority, + channel: ticket.channel, + revision: ticket.revision, + requester: { + association: ticket.requester.association, + ...(ticket.requester.principalId === undefined + ? {} + : { principalId: ticket.requester.principalId }), + ...(ticket.requester.email === undefined + ? {} + : { email: ticket.requester.email }), + }, + ...(ticket.assignedTo === undefined + ? {} + : { assignedTo: ticket.assignedTo }), + createdAt: ticket.createdAt, + updatedAt: ticket.updatedAt, + customerUpdatedAt: ticket.customerUpdatedAt, + ...(ticket.resolvedAt === undefined + ? {} + : { resolvedAt: ticket.resolvedAt }), + ...(ticket.closedAt === undefined ? {} : { closedAt: ticket.closedAt }), + marker: pegSubjectMarker(ticket.number), + }; +} + +function staffMessageDto(message: TicketMessage) { + return { + id: message.id, + ticketId: message.ticketId, + authorKind: message.authorKind, + channel: message.channel, + visibility: message.visibility, + format: message.format, + body: message.body, + createdAt: message.createdAt, + }; +} + +function staffTicketView(view: StaffTicketView) { + return { + ticket: staffTicketDto(view.ticket), + messages: view.messages.map(staffMessageDto), + }; +} + +function staffQueueItemDto(item: StaffQueueItem) { + return { + ticketId: item.ticketId, + revision: item.revision, + status: item.status, + priority: item.priority, + ...(item.category === undefined ? {} : { category: item.category }), + requesterAssociation: item.requesterAssociation, + channel: item.channel, + ...(item.assignedTo === undefined ? {} : { assignedTo: item.assignedTo }), + updatedAt: item.updatedAt, + }; +} + function publicError(error: unknown): ApiError { if (error instanceof ApiError) { return error; @@ -456,16 +577,107 @@ function parseCategory(value: unknown): PegmaSupportCategory { return value as PegmaSupportCategory; } +function parseTicketStatus(value: string): TicketStatus { + if (!TICKET_STATUSES.has(value as TicketStatus)) { + throw new ApiError(400, 'invalid_request'); + } + return value as TicketStatus; +} + +function parseTicketPriority(value: unknown): TicketPriority { + if ( + typeof value !== 'string' || + !TICKET_PRIORITIES.has(value as TicketPriority) + ) { + throw new ApiError(400, 'invalid_request'); + } + return value as TicketPriority; +} + +function parseQueueSort(value: string): QueueSort { + if (!QUEUE_SORTS.has(value as QueueSort)) { + throw new ApiError(400, 'invalid_request'); + } + return value as QueueSort; +} + +function parseStaffPatchAction(value: unknown): StaffPatchAction { + if ( + typeof value !== 'string' || + !STAFF_PATCH_ACTIONS.has(value as StaffPatchAction) + ) { + throw new ApiError(400, 'invalid_request'); + } + return value as StaffPatchAction; +} + +function parseStaffQueueQuery(url: URL): StaffQueueQuery { + const query: { + status?: TicketStatus; + priority?: TicketPriority; + sort?: QueueSort; + unassignedOnly?: boolean; + } = {}; + + const statusParam = url.searchParams.get('status'); + if (statusParam !== null && statusParam !== '') { + query.status = parseTicketStatus(statusParam); + } + + const priorityParam = url.searchParams.get('priority'); + if (priorityParam !== null && priorityParam !== '') { + query.priority = parseTicketPriority(priorityParam); + } + + const sortParam = url.searchParams.get('sort'); + if (sortParam !== null && sortParam !== '') { + query.sort = parseQueueSort(sortParam); + } + + const unassignedOnly = url.searchParams.get('unassignedOnly'); + if (unassignedOnly !== null && unassignedOnly !== '') { + if (unassignedOnly === 'true' || unassignedOnly === '1') { + query.unassignedOnly = true; + } else if (unassignedOnly === 'false' || unassignedOnly === '0') { + query.unassignedOnly = false; + } else { + throw new ApiError(400, 'invalid_request'); + } + } + + return query; +} + +function requireStaffAccess( + authenticated: Authenticated, + allowlist: StaffAllowlist, +) { + const access = staffAccessContext( + authenticated.link.subject, + allowlist, + authenticated.user.email, + ); + if (access === null) { + throw new ApiError(403, 'forbidden'); + } + return access; +} + /** - * Authenticated Support Desk customer API. + * Authenticated Support Desk customer and staff API. * * Session cookie `__Host-pegma_session`, CSRF `X-Pegma-CSRF`, same-origin * Fetch Metadata for mutations. Principal is the Identity subject from the * session — never taken from the request body. + * + * Staff routes live under `/api/support/admin/…` and require host allowlist + * membership (`SUPPORT_STAFF_EMAILS` / `SUPPORT_STAFF_PRINCIPALS`). */ export function createSupportApi( options: SupportApiOptions, ): (request: Request) => Promise { + const staffAllowlist = options.staffAllowlist ?? emptyStaffAllowlist(); + return async (request) => { const url = new URL(request.url); const path = url.pathname; @@ -509,6 +721,198 @@ export function createSupportApi( }); } + // --- Staff admin surface --- + + if (request.method === 'GET' && path === '/api/support/admin/queue') { + const authenticated = await requireAuthentication(request, options); + const access = requireStaffAccess(authenticated, staffAllowlist); + const queueQuery = parseStaffQueueQuery(url); + const result = await options.application.listStaffQueue( + access, + queueQuery, + ); + return json({ + items: result.items.map(staffQueueItemDto), + csrfToken: authenticated.csrfToken, + }); + } + + const adminMatch = ADMIN_TICKET_PATH.exec(path); + if ( + adminMatch !== null && + adminMatch[2] === undefined && + request.method === 'GET' + ) { + const ticketId = adminMatch[1]!; + const authenticated = await requireAuthentication(request, options); + const access = requireStaffAccess(authenticated, staffAllowlist); + const view = await options.application.readStaffTicket( + access, + ticketId, + ); + return json({ + ...staffTicketView(view), + csrfToken: authenticated.csrfToken, + }); + } + + if ( + adminMatch !== null && + adminMatch[2] === undefined && + request.method === 'PATCH' + ) { + requireSameOriginMutation(request); + const ticketId = adminMatch[1]!; + const authenticated = await requireAuthentication(request, options); + await requireCsrf(request, authenticated); + const access = requireStaffAccess(authenticated, staffAllowlist); + + const body = optionalKeysObject( + await readJson(request), + ['action'], + ['priority'], + ); + const action = parseStaffPatchAction(body.action); + const commandId = mintSupportId(); + const correlationId = mintSupportId(); + + let view: StaffTicketView; + switch (action) { + case 'assign': + view = await options.application.assignTicket(access, { + commandId, + correlationId, + ticketId, + assigneeId: authenticated.link.subject, + }); + break; + case 'unassign': + view = await options.application.assignTicket(access, { + commandId, + correlationId, + ticketId, + assigneeId: null, + }); + break; + case 'change_priority': { + if (!Object.hasOwn(body, 'priority')) { + throw new ApiError(400, 'invalid_request'); + } + const priority = parseTicketPriority(body.priority); + view = await options.application.changePriority(access, { + commandId, + correlationId, + ticketId, + priority, + }); + break; + } + case 'resolve': + view = await options.application.resolveTicket(access, { + commandId, + correlationId, + ticketId, + }); + break; + case 'close': + view = await options.application.closeTicket(access, { + commandId, + correlationId, + ticketId, + }); + break; + case 'reopen': + view = await options.application.reopenTicket(access, { + commandId, + correlationId, + ticketId, + }); + break; + default: { + action satisfies never; + throw new ApiError(400, 'invalid_request'); + } + } + + options.logger.log('info', 'support.staff_ticket_patched', { + ticketNumber: view.ticket.number, + action, + }); + + return json(staffTicketView(view)); + } + + if ( + adminMatch !== null && + adminMatch[2] === 'messages' && + request.method === 'POST' + ) { + requireSameOriginMutation(request); + const ticketId = adminMatch[1]!; + const authenticated = await requireAuthentication(request, options); + await requireCsrf(request, authenticated); + await enforceRateLimit( + options.replyLimiter, + authenticated.link.subject, + ); + const access = requireStaffAccess(authenticated, staffAllowlist); + + const body = exactObject(await readJson(request), ['body']); + const messageBody = boundedString(body.body, 1, 20_000, { + allowMultiline: true, + }); + // Mail/outbound notification deferred (Task 10) — omit notification. + const view = await options.application.replyAsStaff(access, { + commandId: mintSupportId(), + correlationId: mintSupportId(), + ticketId, + messageId: mintSupportId(), + body: messageBody, + }); + + options.logger.log('info', 'support.staff_replied', { + ticketNumber: view.ticket.number, + }); + + return json(staffTicketView(view), { status: 201 }); + } + + if ( + adminMatch !== null && + adminMatch[2] === 'notes' && + request.method === 'POST' + ) { + requireSameOriginMutation(request); + const ticketId = adminMatch[1]!; + const authenticated = await requireAuthentication(request, options); + await requireCsrf(request, authenticated); + await enforceRateLimit( + options.replyLimiter, + authenticated.link.subject, + ); + const access = requireStaffAccess(authenticated, staffAllowlist); + + const body = exactObject(await readJson(request), ['body']); + const messageBody = boundedString(body.body, 1, 20_000, { + allowMultiline: true, + }); + const view = await options.application.addNote(access, { + commandId: mintSupportId(), + correlationId: mintSupportId(), + ticketId, + messageId: mintSupportId(), + body: messageBody, + }); + + options.logger.log('info', 'support.staff_note_added', { + ticketNumber: view.ticket.number, + }); + + return json(staffTicketView(view), { status: 201 }); + } + + // --- Customer mutations --- + if (request.method !== 'POST') { throw new ApiError(404, 'not_found'); } diff --git a/worker/src/support-desk.ts b/worker/src/support-desk.ts index 83be4d7..3021364 100644 --- a/worker/src/support-desk.ts +++ b/worker/src/support-desk.ts @@ -152,6 +152,16 @@ export interface SupportRuntimeEnv { readonly IDENTITY_DB: D1Database; /** When `"true"`, health includes a lightweight Support Desk store probe. */ readonly SUPPORT_HEALTH_PROBE?: string; + /** + * Comma-separated verified emails of Support Desk staff operators + * (case-insensitive). Combined with {@link SUPPORT_STAFF_PRINCIPALS}. + */ + readonly SUPPORT_STAFF_EMAILS?: string; + /** + * Comma-separated Identity principal / subject ids of Support Desk staff + * operators. Combined with {@link SUPPORT_STAFF_EMAILS}. + */ + readonly SUPPORT_STAFF_PRINCIPALS?: string; } export interface SupportCompositionOptions { From ebeca41b2e2b47b29cb7af5c0236828aeff93e37 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 29 Jul 2026 11:26:48 -0400 Subject: [PATCH 2/4] fix staff admin posts: authorize before rate-limit debit Non-staff sessions must not consume the shared customer reply limiter before receiving 403 on admin message and note routes. --- worker/src/support-api.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/worker/src/support-api.ts b/worker/src/support-api.ts index 04284e9..b8afce4 100644 --- a/worker/src/support-api.ts +++ b/worker/src/support-api.ts @@ -851,11 +851,13 @@ export function createSupportApi( const ticketId = adminMatch[1]!; const authenticated = await requireAuthentication(request, options); await requireCsrf(request, authenticated); + // Authorize before debiting the shared customer/staff reply limiter so + // non-staff sessions fail closed without mutating quota state. + const access = requireStaffAccess(authenticated, staffAllowlist); await enforceRateLimit( options.replyLimiter, authenticated.link.subject, ); - const access = requireStaffAccess(authenticated, staffAllowlist); const body = exactObject(await readJson(request), ['body']); const messageBody = boundedString(body.body, 1, 20_000, { @@ -886,11 +888,12 @@ export function createSupportApi( const ticketId = adminMatch[1]!; const authenticated = await requireAuthentication(request, options); await requireCsrf(request, authenticated); + // Same order as messages: staff check before shared limiter debit. + const access = requireStaffAccess(authenticated, staffAllowlist); await enforceRateLimit( options.replyLimiter, authenticated.link.subject, ); - const access = requireStaffAccess(authenticated, staffAllowlist); const body = exactObject(await readJson(request), ['body']); const messageBody = boundedString(body.body, 1, 20_000, { From 7df299088907da2940b129efad2cdd09ece877e3 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 29 Jul 2026 11:35:22 -0400 Subject: [PATCH 3/4] fix staff compose: guard against concurrent submissions --- public/staff-support-ticket.js | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/public/staff-support-ticket.js b/public/staff-support-ticket.js index 91dbc1e..1551874 100644 --- a/public/staff-support-ticket.js +++ b/public/staff-support-ticket.js @@ -267,8 +267,11 @@ function bindLifecycle() { composeForm.addEventListener('change', updateComposeEnabled); composeForm.addEventListener('input', updateComposeEnabled); +let composeInFlight = false; + composeForm.addEventListener('submit', async (event) => { event.preventDefault(); + if (composeInFlight) return; const mode = selectedComposeMode(); const body = composeBody.value.trim(); if (mode === '' || body === '') { @@ -281,6 +284,8 @@ composeForm.addEventListener('submit', async (event) => { ? `/api/support/admin/tickets/${encodeURIComponent(ticketId)}/messages` : `/api/support/admin/tickets/${encodeURIComponent(ticketId)}/notes`; + composeInFlight = true; + composeSubmit.disabled = true; try { showStatus(mode === 'public' ? 'Sending public reply…' : 'Saving note…'); const view = await api(path, { @@ -288,11 +293,13 @@ composeForm.addEventListener('submit', async (event) => { body: JSON.stringify({ body }), }); composeForm.reset(); - updateComposeEnabled(); renderTicket(view); showStatus(mode === 'public' ? 'Public reply sent.' : 'Internal note saved.'); } catch (error) { showStatus(`Compose failed: ${error.message}`, true); + } finally { + composeInFlight = false; + updateComposeEnabled(); } }); From c96c09ebd5c889486ba53721c3747c212db2b5f4 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Wed, 29 Jul 2026 11:41:37 -0400 Subject: [PATCH 4/4] fix staff PATCH: reject priority on non-priority actions --- worker/src/support-api.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/worker/src/support-api.ts b/worker/src/support-api.ts index b8afce4..4a6b33b 100644 --- a/worker/src/support-api.ts +++ b/worker/src/support-api.ts @@ -773,6 +773,10 @@ export function createSupportApi( ['priority'], ); const action = parseStaffPatchAction(body.action); + // priority is only meaningful for change_priority — reject silent ignore. + if (action !== 'change_priority' && Object.hasOwn(body, 'priority')) { + throw new ApiError(400, 'invalid_request'); + } const commandId = mintSupportId(); const correlationId = mintSupportId();