diff --git a/docs/SUPPORT_COMPOSITION.md b/docs/SUPPORT_COMPOSITION.md new file mode 100644 index 0000000..87e5edb --- /dev/null +++ b/docs/SUPPORT_COMPOSITION.md @@ -0,0 +1,98 @@ +# Support Desk composition (pegma.dev) + +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. + +## Packages + +Exact published versions: + +- `@pegma/support-desk-application@0.1.0` +- `@pegma/support-desk-contracts@0.1.0` +- `@pegma/support-desk-core@0.1.0` +- `@pegma/support-desk-templates@0.1.0` +- `@pegma/authorization-core@0.1.2` (AccessContext resolution) + +Peers already present on the host: `@pegma/storage-core@0.4.0`, +`@pegma/storage-cloudflare-d1@0.4.0`, `@pegma/sessions@0.1.0`, +`@pegma/rate-limit@0.1.0`, `@pegma/identity@0.1.0`, `@pegma/spine@0.1.1`. + +## Storage namespace + +Support Desk uses the existing `IDENTITY_DB` D1 binding. Isolation is by +collection name, not by sharing Identity mail cursors or session rows: + +| Concern | Collection / host key | +| --- | --- | +| Tickets, messages, audit, commands | `support-desk.records.v1` | +| Customer ticket index | `support-desk.customer-ticket-index.v1` | +| Ticket numbers | `support-desk.ticket-numbers.v1` | +| Queue projection | `support-desk.queue-index.v1` | +| Host maintenance cursors | `pegma-dev-support-maintenance` | + +Identity keeps its own collections and `pegma-dev-maintenance` cursors. The +two never share a cursor key. + +## Authorization + +Any authenticated pegma.dev account receives customer permissions through host +AccessContext defaults (no paid entitlement): + +- `support.ticket.create` +- `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. + +## Categories and markers + +Allowlist: `feedback`, `bug`, `feature_request`, `documentation`, `question`. + +Display marker: `[PEG-{number}]`. Public tracking URL: + +`https://pegma.dev/feedback/ticket/?id={ticketId}` + +## HTTP boundary + +Worker routes (same-origin session + CSRF `X-Pegma-CSRF`): + +| Method | Path | Notes | +| --- | --- | --- | +| `GET` | `/api/support/categories` | Auth required | +| `GET` | `/api/support/tickets` | List own tickets | +| `POST` | `/api/support/tickets` | Create (rate-limited) | +| `GET` | `/api/support/tickets/:id` | Read own; missing/non-owned → same 404 | +| `POST` | `/api/support/tickets/:id/replies` | Reply (rate-limited) | + +Durable rate-limit policies (separate from Identity): + +- `pegma.support.ticket.create` +- `pegma.support.ticket.reply` + +Site pages: `/feedback` (create + list), `/feedback/ticket/?id=…` (read + reply; static shell). + +## 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). + +Health always reports Support Desk package detail without message content. A +store probe runs only when `SUPPORT_HEALTH_PROBE` is exactly `"true"`. + +## Privacy and retention intent + +- Tickets are private conversations between the authenticated requester and + authorized operators. +- Feedback is not automatically published to the roadmap, documentation, or + GitHub Issues. +- Staff UI is deferred. +- 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 + documented further before accepting production-sensitive data at scale. + +Built in the open by RetireGolden, LLC. diff --git a/package-lock.json b/package-lock.json index cf2f64f..e388b0b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,7 @@ "version": "0.1.0", "dependencies": { "@pegma/audit": "0.1.0", + "@pegma/authorization-core": "0.1.2", "@pegma/authorization-identity": "0.1.2", "@pegma/health": "^0.1.1", "@pegma/identity": "0.1.0", @@ -21,6 +22,10 @@ "@pegma/spine": "^0.1.1", "@pegma/storage-cloudflare-d1": "0.4.0", "@pegma/storage-core": "0.4.0", + "@pegma/support-desk-application": "0.1.0", + "@pegma/support-desk-contracts": "0.1.0", + "@pegma/support-desk-core": "0.1.0", + "@pegma/support-desk-templates": "0.1.0", "@pegma/webhooks": "file:vendor/@pegma/webhooks/pegma-webhooks-0.0.0.tgz" }, "devDependencies": { @@ -2294,6 +2299,18 @@ "node": ">=22" } }, + "node_modules/@pegma/authorization-core": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/@pegma/authorization-core/-/authorization-core-0.1.2.tgz", + "integrity": "sha512-Ltj7SbVhRPHypREIJGm/kfbpeWr5coMG6xNzKkKrPfWaWIyYY8wKYmaz+9rzMoBP6Mv3DK0hkSqSMix2ELIYZg==", + "license": "MIT", + "dependencies": { + "@pegma/authorization-contracts": "0.1.2" + }, + "engines": { + "node": ">=22" + } + }, "node_modules/@pegma/authorization-identity": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/@pegma/authorization-identity/-/authorization-identity-0.1.2.tgz", @@ -2471,6 +2488,57 @@ "node": ">=22" } }, + "node_modules/@pegma/support-desk-application": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/@pegma/support-desk-application/-/support-desk-application-0.1.0.tgz", + "integrity": "sha512-nA/Ik9FEeGZy871pOnolv7+pk92J9V45OrtP+4dW6nVPOvAnGu3btAa/3qmc504YLB/xLf5pMJbpOQsRRroYGQ==", + "license": "MIT", + "dependencies": { + "@pegma/audit": "0.1.0", + "@pegma/authorization-core": "0.1.2", + "@pegma/mail": "0.1.0", + "@pegma/spine": "0.1.1", + "@pegma/storage-core": "0.4.0", + "@pegma/support-desk-contracts": "0.1.0", + "@pegma/support-desk-core": "0.1.0" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/@pegma/support-desk-contracts": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/@pegma/support-desk-contracts/-/support-desk-contracts-0.1.0.tgz", + "integrity": "sha512-qG9JjPiQxV4ac0v74QwlCJLKrQXAEm1BVyEmpQvNnOXeW9pq/5pRpD2ThnTMslz0jJDZYQnMnlypH+r5vuK2kg==", + "license": "MIT", + "dependencies": { + "@pegma/spine": "0.1.1" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/@pegma/support-desk-core": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/@pegma/support-desk-core/-/support-desk-core-0.1.0.tgz", + "integrity": "sha512-ILjU9CdF0l2M/+X5l+TG+eMV1ZzUb7Xs2meOsruo4+B5k3YKVwy9J2gIe9BaDlobrn6yBIGe/Sxkxbnh8Sh93g==", + "license": "MIT", + "dependencies": { + "@pegma/support-desk-contracts": "0.1.0" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/@pegma/support-desk-templates": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/@pegma/support-desk-templates/-/support-desk-templates-0.1.0.tgz", + "integrity": "sha512-jp4r37DYdzJwZRyez5O5CHIWmz2gmmgYJY0m8iwWoLtjZ5dGkgUL0QcqBV0T1IB0cZ1lEWo+BoBM9ti8YujdLg==", + "license": "MIT", + "engines": { + "node": ">=22" + } + }, "node_modules/@pegma/webhooks": { "version": "0.0.0", "resolved": "file:vendor/@pegma/webhooks/pegma-webhooks-0.0.0.tgz", diff --git a/package.json b/package.json index 988fccc..5e9dc38 100644 --- a/package.json +++ b/package.json @@ -18,6 +18,7 @@ }, "dependencies": { "@pegma/audit": "0.1.0", + "@pegma/authorization-core": "0.1.2", "@pegma/authorization-identity": "0.1.2", "@pegma/health": "^0.1.1", "@pegma/identity": "0.1.0", @@ -30,6 +31,10 @@ "@pegma/spine": "^0.1.1", "@pegma/storage-cloudflare-d1": "0.4.0", "@pegma/storage-core": "0.4.0", + "@pegma/support-desk-application": "0.1.0", + "@pegma/support-desk-contracts": "0.1.0", + "@pegma/support-desk-core": "0.1.0", + "@pegma/support-desk-templates": "0.1.0", "@pegma/webhooks": "file:vendor/@pegma/webhooks/pegma-webhooks-0.0.0.tgz" }, "devDependencies": { diff --git a/public/feedback-ticket.js b/public/feedback-ticket.js new file mode 100644 index 0000000..2fb4a07 --- /dev/null +++ b/public/feedback-ticket.js @@ -0,0 +1,134 @@ +const statusNode = document.querySelector('#ticket-status'); +const signedOut = document.querySelector('#ticket-signed-out'); +const detail = document.querySelector('#ticket-detail'); +const heading = document.querySelector('#ticket-heading'); +const meta = document.querySelector('#ticket-meta'); +const messageList = document.querySelector('#message-list'); +const replyForm = document.querySelector('#reply-form'); +const ticketId = new URL(window.location.href).searchParams.get('id') ?? ''; + +let csrfToken = ''; + +function showStatus(message, isError = false) { + statusNode.textContent = message; + statusNode.dataset.tone = isError ? 'error' : 'neutral'; +} + +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 renderMessages(messages) { + messageList.replaceChildren(); + for (const message of messages) { + const item = document.createElement('li'); + const who = document.createElement('strong'); + who.textContent = + message.authorKind === 'customer' + ? 'You' + : message.authorKind === 'staff' + ? 'Pegma' + : 'System'; + 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) { + heading.textContent = `${view.ticket.marker} ${view.ticket.subject}`; + meta.textContent = `${view.ticket.status} · ${view.ticket.category ?? 'uncategorized'}`; + renderMessages(view.messages); +} + +async function loadTicket() { + if (ticketId === '') { + showStatus('Missing ticket id.', true); + return; + } + const idDisplay = document.querySelector('#ticket-id-display'); + if (idDisplay) idDisplay.textContent = ticketId; + try { + await api('/api/identity/account'); + } catch (error) { + if (error.status === 401) { + signedOut.hidden = false; + detail.hidden = true; + showStatus('Sign in to view this ticket.'); + return; + } + throw error; + } + + try { + const view = await api( + `/api/support/tickets/${encodeURIComponent(ticketId)}`, + ); + if (typeof view.csrfToken === 'string') { + csrfToken = view.csrfToken; + } + signedOut.hidden = true; + detail.hidden = false; + renderTicket(view); + showStatus('Ticket loaded.'); + } catch (error) { + signedOut.hidden = true; + detail.hidden = true; + if (error.status === 401) { + signedOut.hidden = false; + showStatus('Sign in to view this ticket.'); + return; + } + if (error.status === 404) { + showStatus('Ticket not found.', true); + return; + } + showStatus(`Could not load ticket: ${error.message}`, true); + } +} + +replyForm.addEventListener('submit', async (event) => { + event.preventDefault(); + try { + const form = new FormData(replyForm); + showStatus('Sending reply…'); + const view = await api( + `/api/support/tickets/${encodeURIComponent(ticketId)}/replies`, + { + method: 'POST', + body: JSON.stringify({ body: form.get('body') }), + }, + ); + replyForm.reset(); + renderTicket(view); + showStatus('Reply sent.'); + } catch (error) { + showStatus(`Could not send reply: ${error.message}`, true); + } +}); + +loadTicket(); diff --git a/public/feedback.js b/public/feedback.js new file mode 100644 index 0000000..78a9989 --- /dev/null +++ b/public/feedback.js @@ -0,0 +1,112 @@ +const statusNode = document.querySelector('#feedback-status'); +const signedOut = document.querySelector('#feedback-signed-out'); +const signedIn = document.querySelector('#feedback-signed-in'); +const emailNode = document.querySelector('#feedback-email'); +const ticketList = document.querySelector('#ticket-list'); +const createForm = document.querySelector('#create-ticket'); + +let csrfToken = ''; + +function showStatus(message, isError = false) { + statusNode.textContent = message; + statusNode.dataset.tone = isError ? 'error' : 'neutral'; +} + +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 renderTickets(tickets) { + ticketList.replaceChildren(); + if (tickets.length === 0) { + const empty = document.createElement('li'); + empty.textContent = 'No tickets yet.'; + ticketList.append(empty); + return; + } + for (const ticket of tickets) { + const item = document.createElement('li'); + const link = document.createElement('a'); + link.href = `/feedback/ticket/?id=${encodeURIComponent(ticket.id)}`; + link.textContent = `${ticket.marker} ${ticket.subject}`; + const meta = document.createElement('span'); + meta.className = 'form-note'; + meta.textContent = `${ticket.status} · ${ticket.category ?? 'uncategorized'}`; + item.append(link, meta); + ticketList.append(item); + } +} + +async function refreshTickets() { + const result = await api('/api/support/tickets'); + if (typeof result.csrfToken === 'string') { + csrfToken = result.csrfToken; + } + renderTickets(result.tickets); +} + +async function start() { + try { + const account = await api('/api/identity/account'); + csrfToken = account.csrfToken; + emailNode.textContent = account.account.email; + signedOut.hidden = true; + signedIn.hidden = false; + await refreshTickets(); + showStatus('You can submit private feedback.'); + } catch (error) { + if (error.status === 401) { + csrfToken = ''; + signedIn.hidden = true; + signedOut.hidden = false; + showStatus('Sign in to submit or track feedback.'); + return; + } + showStatus(`Feedback is unavailable: ${error.message}`, true); + } +} + +createForm.addEventListener('submit', async (event) => { + event.preventDefault(); + try { + const form = new FormData(createForm); + showStatus('Submitting ticket…'); + const created = await api('/api/support/tickets', { + method: 'POST', + body: JSON.stringify({ + subject: form.get('subject'), + body: form.get('body'), + category: form.get('category'), + }), + }); + createForm.reset(); + await refreshTickets(); + showStatus( + `Ticket ${created.ticket.marker} created. Open it from the list below.`, + ); + } catch (error) { + showStatus(`Could not create ticket: ${error.message}`, true); + } +}); + +start(); diff --git a/src/layouts/Base.astro b/src/layouts/Base.astro index aa8d04a..7d7b70c 100644 --- a/src/layouts/Base.astro +++ b/src/layouts/Base.astro @@ -13,6 +13,7 @@ const nav = [ { href: '/stack', label: 'The stack' }, { href: '/roadmap', label: 'Roadmap' }, { href: '/examples', label: 'Examples' }, + { href: '/feedback', label: 'Feedback' }, { href: '/account', label: 'Account' }, ]; --- diff --git a/src/pages/account.astro b/src/pages/account.astro index 3a30cd1..ccd8a7f 100644 --- a/src/pages/account.astro +++ b/src/pages/account.astro @@ -67,6 +67,13 @@ import Base from '../layouts/Base.astro';

Call a protected Worker endpoint that resolves this browser session through @pegma/sessions.

+

Product feedback

+

+ Submit private product feedback and track tickets you own. Tickets stay private; + they are not published to the roadmap or GitHub Issues. +

+

Open feedback

+

Passkeys

diff --git a/src/pages/feedback.astro b/src/pages/feedback.astro new file mode 100644 index 0000000..91cd102 --- /dev/null +++ b/src/pages/feedback.astro @@ -0,0 +1,92 @@ +--- +import Base from '../layouts/Base.astro'; +--- + + +
+

Authenticated product feedback

+

Feedback

+

+ Signed-in accounts can open private tickets for product feedback, bugs, + feature requests, documentation issues, and questions. Tickets stay private + to you and authorized operators — they are not published to the roadmap or + GitHub Issues. +

+
+ +
+ Checking your session… +
+ + + +
+ + + + + diff --git a/src/pages/feedback/ticket.astro b/src/pages/feedback/ticket.astro new file mode 100644 index 0000000..4d3d7ad --- /dev/null +++ b/src/pages/feedback/ticket.astro @@ -0,0 +1,51 @@ +--- +import Base from '../../layouts/Base.astro'; +--- + + +
+

Your ticket

+

Loading…

+

+ Private conversation for ticket + …. Only you and authorized operators can + read this thread. +

+
+ +
+ Loading ticket… +
+ + + + + + + diff --git a/src/styles/global.css b/src/styles/global.css index 0518656..8d589e3 100644 --- a/src/styles/global.css +++ b/src/styles/global.css @@ -394,9 +394,13 @@ h2 { font-weight: 650; } -.account-form input { +.account-form input, +.account-form select, +.account-form textarea { min-width: 0; flex: 1; + width: 100%; + margin-bottom: 0.85rem; padding: 0.65rem 0.75rem; border: 1px solid var(--line); border-radius: 0.4rem; @@ -405,6 +409,38 @@ h2 { font: inherit; } +.account-form textarea { + resize: vertical; +} + +.ticket-list, +.message-list { + padding: 0; + list-style: none; +} + +.ticket-list li, +.message-list li { + padding: 0.75rem 0; + border-bottom: 1px solid var(--line); +} + +.ticket-list li { + display: flex; + flex-direction: column; + gap: 0.2rem; +} + +.message-list li p { + margin: 0.4rem 0 0; + white-space: pre-wrap; +} + +#feedback-status[data-tone="error"], +#ticket-status[data-tone="error"] { + border-left-color: #a33; +} + button { padding: 0.65rem 0.9rem; border: 1px solid var(--ink); @@ -427,6 +463,15 @@ button:disabled { color: var(--ink); } +a.secondary-button { + display: inline-block; + text-decoration: none; + padding: 0.65rem 0.9rem; + border: 1px solid var(--ink); + border-radius: 0.4rem; + font-weight: 650; +} + .text-button { padding: 0.25rem 0.45rem; border-color: var(--line); @@ -461,7 +506,8 @@ button:disabled { } .account-inline button, - .account-heading button { + .account-heading button, + .account-heading a.secondary-button { width: 100%; } } diff --git a/worker/README.md b/worker/README.md index 6c25ab2..3ddf8d1 100644 --- a/worker/README.md +++ b/worker/README.md @@ -165,6 +165,27 @@ must remain disabled until the host also has an authenticated, audited operator acknowledgement workflow; this Worker intentionally exposes no public acknowledgement endpoint. +## Support Desk composition + +Authenticated product feedback uses exact `@pegma/support-desk-*@0.1.0` over +the same `IDENTITY_DB` D1 binding. Support Desk collections +(`support-desk.*.v1`) and host cursor collection +`pegma-dev-support-maintenance` are isolated from Identity mail cursors and +session rows. Customer permissions are granted to any authenticated account +via AccessContext defaults (not a paid entitlement). Categories: +`feedback`, `bug`, `feature_request`, `documentation`, `question`. Subject +marker: `[PEG-…]`. Tracking pages: `/feedback` and `/feedback/{ticketId}`. + +Create and reply use durable rate limits `pegma.support.ticket.create` and +`pegma.support.ticket.reply`. Minute maintenance runs queue repair and +inactive projection sweep with independent cursors. Notifications on +create/reply are omitted in this slice; Pegma templates are composed for a +later mail activation. Health lists Support Desk package detail without +message content; set `SUPPORT_HEALTH_PROBE=true` only when an explicit store +probe is wanted. + +See `docs/SUPPORT_COMPOSITION.md`. + ## Endpoints - `GET /`, `GET /health`, or `GET /api/health` — JSON from `@pegma/health` @@ -183,6 +204,12 @@ public acknowledgement endpoint. - `POST /api/identity/email-code/sign-in/options|verify` — enumeration-safe fallback sign-in. - `POST /api/identity/logout` — server-side revocation and cookie expiry. +- `GET /api/support/categories` — authenticated category allowlist. +- `GET /api/support/tickets` — list the caller's tickets. +- `POST /api/support/tickets` — create a ticket (CSRF + durable rate limit). +- `GET /api/support/tickets/:id` — read an owned ticket; missing and non-owned + tickets share one content-free `404`. +- `POST /api/support/tickets/:id/replies` — customer reply (CSRF + rate limit). - `GET /api/releases` — public current-stable release summaries for allowlisted Pegma repositories, in component-registry order. JSON schema `pegma.releases.v1`; short public cache (`max-age=300`) and `ETag`; no diff --git a/worker/src/index.ts b/worker/src/index.ts index 4f654a5..e2cf284 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -4,6 +4,7 @@ import { runHealthChecks, toHealthResponse, } from '@pegma/health'; +import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity'; import { runIdentityMaintenance } from './identity-maintenance'; import { createAppLogger, type LoggerEnv } from './logger'; import { @@ -22,8 +23,40 @@ import { runReleaseReconciliation, } from './release-reconciliation'; import { handleGetReleases, readReleasesConfig } from './releases-api'; +import { createSupportApi } from './support-api'; +import { + createProductionSupportRuntime, + probeSupportStore, + supportHealthProbeEnabled, + type SupportRuntimeEnv, +} from './support-desk'; +import { runSupportMaintenance } from './support-maintenance'; + +type AppEnv = Env & + LoggerEnv & + IdentityRuntimeEnv & + GitHubReleaseWebhookEnv & + SupportRuntimeEnv; -type AppEnv = Env & LoggerEnv & IdentityRuntimeEnv & GitHubReleaseWebhookEnv; +function createSupportHandler(env: AppEnv, logger: ReturnType) { + const identityRuntime = createProductionIdentityRuntime(env, logger); + const supportRuntime = createProductionSupportRuntime(env, { + sessions: identityRuntime.sessions, + identity: identityRuntime.identity, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + logger, + }); + const api = createSupportApi({ + application: supportRuntime.application, + sessions: supportRuntime.sessions, + identity: supportRuntime.identity, + identityLinkFromClaims: supportRuntime.identityLinkFromClaims, + createLimiter: supportRuntime.createLimiter, + replyLimiter: supportRuntime.replyLimiter, + logger, + }); + return { supportRuntime, api }; +} /** * Thin Workers slice that proves pegma.dev's Pegma Logger wiring: @@ -68,6 +101,35 @@ export default { error: error instanceof Error ? error.name : 'unknown', }); } + + let supportDetail: { + storage: 'cloudflare-d1'; + packages: string; + probe: 'disabled' | 'ok' | 'fail'; + } = { + storage: 'cloudflare-d1', + packages: '@pegma/support-desk-application@0.1.0', + probe: 'disabled', + }; + if (supportHealthProbeEnabled(env)) { + try { + const identityRuntime = createProductionIdentityRuntime(env, logger); + const supportRuntime = createProductionSupportRuntime(env, { + sessions: identityRuntime.sessions, + identity: identityRuntime.identity, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + logger, + }); + const probe = await probeSupportStore(supportRuntime.store); + supportDetail = { + ...supportDetail, + probe: probe.ok ? 'ok' : 'fail', + }; + } catch { + supportDetail = { ...supportDetail, probe: 'fail' }; + } + } + const result = await runHealthChecks({ service: 'pegma-dev-api', logger, @@ -86,6 +148,7 @@ export default { String(env.IDENTITY_EMAIL_ENABLED) === 'true' && Boolean(env.RESEND_API_KEY), }), + createDetailCheck('supportDesk', supportDetail), createDetailCheck('githubReleases', { ingestionConfigured: releaseDetail.ingestionConfigured, readConfigured: releaseDetail.readConfigured, @@ -204,6 +267,27 @@ export default { } } + if (path.startsWith('/api/support/')) { + try { + return await createSupportHandler(env, logger).api(request); + } catch (error) { + logger.log('error', 'support.runtime_unavailable', { + error: error instanceof Error ? error.name : 'unknown', + }); + return Response.json( + { error: 'support_unavailable' }, + { + status: 503, + headers: { + 'Cache-Control': 'no-store', + 'Content-Type': 'application/json; charset=utf-8', + 'X-Content-Type-Options': 'nosniff', + }, + }, + ); + } + } + logger.log('warn', 'request.not_found', { method: request.method, path }); return new Response('Not Found', { status: 404 }); }, @@ -253,5 +337,33 @@ export default { } })(), ); + + ctx.waitUntil( + (async () => { + try { + const identityRuntime = createProductionIdentityRuntime(env, logger); + const supportRuntime = createProductionSupportRuntime(env, { + sessions: identityRuntime.sessions, + identity: identityRuntime.identity, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + logger, + }); + await runSupportMaintenance( + { + store: supportRuntime.store, + clock: supportRuntime.clock, + limiters: supportRuntime.limiters, + terminalRetentionMilliseconds: + supportRuntime.terminalRetentionMilliseconds, + }, + logger, + ); + } catch (error) { + logger.log('error', 'support.maintenance_unavailable', { + error: error instanceof Error ? error.name : 'unknown', + }); + } + })(), + ); }, } satisfies ExportedHandler; diff --git a/worker/src/support-access.ts b/worker/src/support-access.ts new file mode 100644 index 0000000..df98497 --- /dev/null +++ b/worker/src/support-access.ts @@ -0,0 +1,37 @@ +import { resolveAccess, type AccessContext } from '@pegma/authorization-core'; +import type { PrincipalId } from '@pegma/spine'; +import { supportPermissions } from '@pegma/support-desk-application'; + +/** + * Host policy version for pegma.dev product feedback. + * + * Customer permissions are granted to any authenticated account via defaults — + * not a paid entitlement or invented multi-tenant role. + */ +export const SUPPORT_CUSTOMER_POLICY_VERSION = + 'pegma.dev-support-customer-1' as const; + +/** Customer permission set for authenticated pegma.dev accounts. */ +export const SUPPORT_CUSTOMER_PERMISSIONS = Object.freeze([ + supportPermissions.create, + supportPermissions.readOwn, + supportPermissions.replyOwn, +] as const); + +/** + * Resolve an AccessContext for an authenticated Identity principal. + * + * `principalId` must be the opaque Identity subject / account id from the + * server-side session (never a browser-supplied claim). + */ +export function customerAccessContext( + principalId: PrincipalId, +): AccessContext { + return resolveAccess( + { principalId }, + { + version: SUPPORT_CUSTOMER_POLICY_VERSION, + defaults: [...SUPPORT_CUSTOMER_PERMISSIONS], + }, + ); +} diff --git a/worker/src/support-api.test.ts b/worker/src/support-api.test.ts new file mode 100644 index 0000000..fdb5fb9 --- /dev/null +++ b/worker/src/support-api.test.ts @@ -0,0 +1,445 @@ +import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity'; +import { createMemoryStore } from '@pegma/storage-core'; +import { createSessionStore } from '@pegma/sessions'; +import { fixedClock, type Logger, type PrincipalId } from '@pegma/spine'; +import { + SupportDeskNotFoundError, + type SupportDeskApplication, +} from '@pegma/support-desk-application'; +import { describe, expect, it, vi } from 'vitest'; +import { + IDENTITY_ISSUER, + SESSION_COOKIE, +} from './identity-api'; +import type { + IdentityPort, + IdentityUser, + VerifiedIdentityClaims, +} from './identity-contracts'; +import { createSupportApi } from './support-api'; +import { customerAccessContext } from './support-access'; +import { + createSupportRuntime, + formatPegmaTicketSubject, + mapSupportError, + pegSubjectMarker, + publicTicketUrl, +} from './support-desk'; +import { + readSupportCursor, + saveSupportCursor, +} from './support-cursors'; +import { runSupportMaintenance } from './support-maintenance'; + +const principalA = 'principal-a' as PrincipalId; +const principalB = 'principal-b' as PrincipalId; +const clock = fixedClock('2026-07-29T12:00:00.000Z'); +const logger: Logger = { log: vi.fn() }; + +function userFor(principalId: PrincipalId, email: string): IdentityUser { + return { + principalId, + email, + emailVerified: true, + status: 'active', + createdAt: '2026-07-29T00:00:00.000Z', + updatedAt: '2026-07-29T00:00:00.000Z', + }; +} + +function identityFor( + users: ReadonlyMap, +): IdentityPort { + return { + claimsFor: vi.fn(async (principalId: PrincipalId) => { + const user = users.get(principalId); + if (user === undefined) { + throw Object.assign(new Error('not found'), { code: 'not_found' }); + } + return { + issuer: IDENTITY_ISSUER, + subject: principalId, + emailVerified: true, + } satisfies VerifiedIdentityClaims; + }), + getUser: vi.fn(async (principalId: PrincipalId) => users.get(principalId) ?? null), + beginPasskeyRegistration: vi.fn(), + finishPasskeyRegistration: vi.fn(), + beginPasskeyAuthentication: vi.fn(), + finishPasskeyAuthentication: vi.fn(), + listPasskeys: vi.fn(async () => []), + removePasskey: vi.fn(async () => true), + }; +} + +let sessionSerial = 0; + +async function sessionCookie( + sessions: ReturnType, + principalId: PrincipalId, + csrfToken = 'c'.repeat(43), +): Promise<{ cookie: string; csrfToken: string }> { + sessionSerial += 1; + const sessionId = `${String(sessionSerial).padStart(2, '0')}${'s'.repeat(41)}`; + await sessions.create(sessionId, { + principalId, + data: JSON.stringify({ + version: 1, + csrfToken, + issuer: IDENTITY_ISSUER, + subject: principalId, + }), + }); + return { + cookie: `${SESSION_COOKIE}=${sessionId}`, + csrfToken, + }; +} + +function get(path: string, cookie?: string): Request { + return new Request(`https://pegma.dev${path}`, { + headers: cookie === undefined ? {} : { Cookie: cookie }, + }); +} + +function post( + path: string, + body: unknown, + headers: Record = {}, +): Request { + return new Request(`https://pegma.dev${path}`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Origin: IDENTITY_ISSUER, + 'Sec-Fetch-Site': 'same-origin', + ...headers, + }, + body: JSON.stringify(body), + }); +} + +function fixture() { + const store = createMemoryStore(); + const sessions = createSessionStore(store, { logger }); + const users = new Map([ + [principalA, userFor(principalA, 'a@example.test')], + [principalB, userFor(principalB, 'b@example.test')], + ]); + const identity = identityFor(users); + const runtime = createSupportRuntime({ + store, + sessions, + identity, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + logger, + clock, + }); + const api = createSupportApi({ + application: runtime.application, + sessions, + identity, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + createLimiter: runtime.createLimiter, + replyLimiter: runtime.replyLimiter, + logger, + }); + return { store, sessions, runtime, api, application: runtime.application }; +} + +describe('support subject markers and URLs', () => { + it('formats [PEG-…] markers and public ticket URLs', () => { + expect(pegSubjectMarker(1042)).toBe('[PEG-1042]'); + expect(formatPegmaTicketSubject(7, 'Docs typo')).toBe( + '[PEG-7] Docs typo', + ); + expect(publicTicketUrl('ticket-1')).toBe( + 'https://pegma.dev/feedback/ticket/?id=ticket-1', + ); + }); +}); + +describe('customer access defaults', () => { + it('grants create/read-own/reply-own without a paid entitlement', () => { + const access = customerAccessContext(principalA); + expect(access.principalId).toBe(principalA); + expect(access.entitlements).toEqual([]); + expect(access.permissions).toEqual( + expect.arrayContaining([ + 'support.ticket.create', + 'support.ticket.read.own', + 'support.ticket.reply.own', + ]), + ); + }); +}); + +describe('authenticated support API', () => { + it('requires authentication for list and create', async () => { + const { api } = fixture(); + const list = await api(get('/api/support/tickets')); + expect(list.status).toBe(401); + expect(await list.json()).toEqual({ error: 'authentication_required' }); + + const create = await api( + post('/api/support/tickets', { + subject: 'Hello', + body: 'Details', + category: 'feedback', + }), + ); + expect(create.status).toBe(401); + }); + + it('creates, lists, reads, and replies for the owning principal', async () => { + const { api, sessions } = fixture(); + const auth = await sessionCookie(sessions, principalA); + + 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 createdBody = (await created.json()) as { + ticket: { + id: string; + number: number; + subject: string; + category: string; + marker: string; + url: string; + }; + messages: readonly { body: string; authorKind: string }[]; + }; + expect(createdBody.ticket.subject).toBe('Roadmap clarity'); + expect(createdBody.ticket.category).toBe('feedback'); + expect(createdBody.ticket.number).toBe(1); + expect(createdBody.ticket.marker).toBe('[PEG-1]'); + expect(createdBody.ticket.url).toBe( + `https://pegma.dev/feedback/ticket/?id=${createdBody.ticket.id}`, + ); + expect(createdBody.messages).toHaveLength(1); + expect(createdBody.messages[0]?.body).toContain('hard to scan'); + expect(createdBody.messages[0]?.authorKind).toBe('customer'); + + const listed = await api(get('/api/support/tickets', auth.cookie)); + expect(listed.status).toBe(200); + const listBody = (await listed.json()) as { + tickets: readonly { id: string }[]; + }; + expect(listBody.tickets).toHaveLength(1); + expect(listBody.tickets[0]?.id).toBe(createdBody.ticket.id); + + const read = await api( + get(`/api/support/tickets/${createdBody.ticket.id}`, auth.cookie), + ); + expect(read.status).toBe(200); + const readBody = (await read.json()) as { + ticket: { id: string }; + messages: readonly unknown[]; + }; + expect(readBody.ticket.id).toBe(createdBody.ticket.id); + expect(readBody.messages).toHaveLength(1); + + const replied = await api( + post( + `/api/support/tickets/${createdBody.ticket.id}/replies`, + { body: 'Also the mobile layout wraps oddly.' }, + { + Cookie: auth.cookie, + 'X-Pegma-CSRF': auth.csrfToken, + }, + ), + ); + expect(replied.status).toBe(201); + const replyBody = (await replied.json()) as { + messages: readonly { body: string }[]; + }; + expect(replyBody.messages).toHaveLength(2); + expect(replyBody.messages[1]?.body).toContain('mobile layout'); + }); + + it('returns content-free 404 for missing and non-owned tickets', async () => { + const { api, sessions } = fixture(); + const owner = await sessionCookie(sessions, principalA, 'a'.repeat(43)); + const other = await sessionCookie(sessions, principalB, 'b'.repeat(43)); + + const created = await api( + post( + '/api/support/tickets', + { + subject: 'Private', + body: 'Should not leak to another principal.', + category: 'bug', + }, + { + Cookie: owner.cookie, + 'X-Pegma-CSRF': owner.csrfToken, + }, + ), + ); + const { ticket } = (await created.json()) as { ticket: { id: string } }; + + const missing = await api( + get('/api/support/tickets/does-not-exist', owner.cookie), + ); + const foreign = await api( + get(`/api/support/tickets/${ticket.id}`, other.cookie), + ); + + expect(missing.status).toBe(404); + expect(foreign.status).toBe(404); + expect(await missing.json()).toEqual({ error: 'not_found' }); + expect(await foreign.json()).toEqual({ error: 'not_found' }); + }); + + it('requires CSRF and same-origin metadata for mutations', async () => { + const { api, sessions } = fixture(); + const auth = await sessionCookie(sessions, principalA); + + const noCsrf = await api( + post( + '/api/support/tickets', + { + subject: 'No CSRF', + body: 'Should fail.', + category: 'question', + }, + { Cookie: auth.cookie }, + ), + ); + expect(noCsrf.status).toBe(403); + expect(await noCsrf.json()).toEqual({ error: 'csrf_denied' }); + + const crossOrigin = await api( + new Request('https://pegma.dev/api/support/tickets', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Origin: 'https://evil.example', + 'Sec-Fetch-Site': 'cross-site', + Cookie: auth.cookie, + 'X-Pegma-CSRF': auth.csrfToken, + }, + body: JSON.stringify({ + subject: 'Cross origin', + body: 'Should fail.', + category: 'question', + }), + }), + ); + expect(crossOrigin.status).toBe(403); + expect(await crossOrigin.json()).toEqual({ error: 'cross_origin_denied' }); + }); + + it('rejects invalid categories without leaking allowlist internals', async () => { + const { api, sessions } = fixture(); + const auth = await sessionCookie(sessions, principalA); + const response = await api( + post( + '/api/support/tickets', + { + subject: 'Bad category', + body: 'Body', + category: 'billing', + }, + { + Cookie: auth.cookie, + 'X-Pegma-CSRF': auth.csrfToken, + }, + ), + ); + expect(response.status).toBe(400); + expect(await response.json()).toEqual({ error: 'invalid_category' }); + }); +}); + +describe('support error mapping', () => { + it('maps missing tickets to content-free 404', () => { + expect(mapSupportError(new SupportDeskNotFoundError())).toEqual({ + status: 404, + code: 'not_found', + }); + }); +}); + +describe('support maintenance cursors', () => { + it('persists independent queue cursors and runs repair/sweep', async () => { + const { store, runtime } = fixture(); + await saveSupportCursor(store, 'queueRepairCursor', 'cursor-repair-1'); + await saveSupportCursor( + store, + 'queueInactiveSweepCursor', + 'cursor-inactive-1', + ); + + expect(await readSupportCursor(store, 'queueRepairCursor')).toBe( + 'cursor-repair-1', + ); + expect(await readSupportCursor(store, 'queueInactiveSweepCursor')).toBe( + 'cursor-inactive-1', + ); + // Identity-style keys must not collide: only the named Support field changes. + await saveSupportCursor(store, 'queueRepairCursor', 'cursor-repair-2'); + expect(await readSupportCursor(store, 'queueRepairCursor')).toBe( + 'cursor-repair-2', + ); + expect(await readSupportCursor(store, 'queueInactiveSweepCursor')).toBe( + 'cursor-inactive-1', + ); + + await runSupportMaintenance( + { + store, + clock, + limiters: runtime.limiters, + terminalRetentionMilliseconds: runtime.terminalRetentionMilliseconds, + }, + logger, + ); + + // Maintenance completes without throwing; a stale opaque cursor may remain + // until a successful page starts from a valid position, so only require + // that the two loop keys stay independently addressable. + const repair = await readSupportCursor(store, 'queueRepairCursor'); + const inactive = await readSupportCursor(store, 'queueInactiveSweepCursor'); + expect(repair === undefined || typeof repair === 'string').toBe(true); + expect(inactive === undefined || typeof inactive === 'string').toBe(true); + }); +}); + +describe('application ownership boundary', () => { + it('uses the session principal for create ownership', async () => { + const { application } = fixture() as { + application: SupportDeskApplication; + }; + const accessA = customerAccessContext(principalA); + const created = await application.createCustomerTicket(accessA, { + commandId: 'cmd-1', + correlationId: 'corr-1', + ticketId: 'ticket-owned', + messageId: 'msg-1', + subject: 'Ownership', + body: 'Body', + category: 'documentation', + }); + expect(created.ticket.id).toBe('ticket-owned'); + + await expect( + application.readCustomerTicket( + customerAccessContext(principalB), + 'ticket-owned', + ), + ).rejects.toBeInstanceOf(SupportDeskNotFoundError); + }); +}); diff --git a/worker/src/support-api.ts b/worker/src/support-api.ts new file mode 100644 index 0000000..5d76fd7 --- /dev/null +++ b/worker/src/support-api.ts @@ -0,0 +1,618 @@ +import type { Logger, PrincipalId } from '@pegma/spine'; +import type { SessionStore } from '@pegma/sessions'; +import type { DurableRateLimiter } from '@pegma/rate-limit'; +import type { + CustomerTicketSummary, + CustomerTicketView, + SupportDeskApplication, +} from '@pegma/support-desk-application'; +import { + IDENTITY_ISSUER, + SESSION_COOKIE, +} from './identity-api'; +import type { + IdentityLinkKey, + IdentityLinkProjector, + IdentityPort, + IdentityUser, + VerifiedIdentityClaims, +} from './identity-contracts'; +import { customerAccessContext } from './support-access'; +import { + mapSupportError, + mintSupportId, + pegSubjectMarker, + PEGMA_SUPPORT_CATEGORIES, + PEGMA_SUPPORT_CATEGORY_SET, + publicTicketUrl, + type PegmaSupportCategory, +} from './support-desk'; + +const JSON_LIMIT = 64 * 1024; +const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/u; +const SESSION_DATA_KEYS = new Set([ + 'version', + 'csrfToken', + 'issuer', + 'subject', +]); +const TICKET_ID_PATH = + /^\/api\/support\/tickets\/([A-Za-z0-9._~-]{1,200})(?:\/(replies))?$/u; + +interface SupportApiOptions { + readonly application: SupportDeskApplication; + readonly sessions: SessionStore; + readonly identity: IdentityPort; + readonly identityLinkFromClaims: IdentityLinkProjector; + readonly createLimiter: DurableRateLimiter; + readonly replyLimiter: DurableRateLimiter; + readonly logger: Logger; +} + +interface SessionData { + readonly version: 1; + readonly csrfToken: string; + readonly issuer: typeof IDENTITY_ISSUER; + readonly subject: PrincipalId; +} + +interface Authenticated { + readonly rawSessionId: string; + readonly csrfToken: string; + readonly link: IdentityLinkKey; + readonly user: IdentityUser; +} + +class ApiError extends Error { + constructor( + readonly status: number, + readonly code: string, + readonly retryAfterSeconds?: number, + ) { + super(code); + } +} + +class InvalidatedSessionError extends ApiError { + constructor() { + super(401, 'authentication_required'); + } +} + +function json( + body: unknown, + init: ResponseInit = {}, +): Response { + const headers = new Headers(init.headers); + headers.set('Cache-Control', 'no-store'); + headers.set('Pragma', 'no-cache'); + headers.set('Content-Type', 'application/json; charset=utf-8'); + headers.set('X-Content-Type-Options', 'nosniff'); + headers.set('Vary', 'Cookie'); + return Response.json(body, { ...init, headers }); +} + +function cookieValue(request: Request, name: string): string | null { + const header = request.headers.get('Cookie'); + if (header === null || header.length > 8_192) { + return null; + } + let found: string | null = null; + for (const part of header.split(';')) { + const separator = part.indexOf('='); + if (separator < 0 || part.slice(0, separator).trim() !== name) { + continue; + } + if (found !== null) { + return null; + } + found = part.slice(separator + 1).trim(); + } + return found !== null && TOKEN_PATTERN.test(found) ? found : null; +} + +function isPlainObject(value: unknown): value is Record { + return ( + typeof value === 'object' && + value !== null && + !Array.isArray(value) && + Object.getPrototypeOf(value) === Object.prototype + ); +} + +function exactObject( + value: unknown, + keys: readonly string[], +): Record { + if ( + !isPlainObject(value) || + Object.keys(value).length !== keys.length || + keys.some((key) => !Object.hasOwn(value, key)) + ) { + throw new ApiError(400, 'invalid_request'); + } + return value; +} + +function optionalKeysObject( + value: unknown, + required: readonly string[], + optional: readonly string[], +): Record { + if (!isPlainObject(value)) { + throw new ApiError(400, 'invalid_request'); + } + const allowed = new Set([...required, ...optional]); + const keys = Object.keys(value); + if ( + keys.some((key) => !allowed.has(key)) || + required.some((key) => !Object.hasOwn(value, key)) + ) { + throw new ApiError(400, 'invalid_request'); + } + return value; +} + +/** + * Validate a host-supplied string. + * @param options.allowMultiline When true, HT LF/CR/TAB are permitted (message + * bodies from textareas). Other C0/C1 controls remain rejected. + */ +function boundedString( + value: unknown, + minimum: number, + maximum: number, + options: { allowMultiline?: boolean } = {}, +): string { + if ( + typeof value !== 'string' || + value.length < minimum || + value.length > maximum + ) { + throw new ApiError(400, 'invalid_request'); + } + // Never write literal control characters into source; use escapes. + // Multiline fields may include \t, \n, \r only. + const controlPattern = options.allowMultiline + ? /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/u + : /[\u0000-\u001F\u007F-\u009F]/u; + if (controlPattern.test(value)) { + throw new ApiError(400, 'invalid_request'); + } + return value; +} + +async function readJson(request: Request): Promise { + const contentType = request.headers.get('Content-Type')?.split(';', 1)[0]; + if (contentType?.trim().toLowerCase() !== 'application/json') { + throw new ApiError(415, 'json_required'); + } + const declaredLength = request.headers.get('Content-Length'); + if ( + declaredLength !== null && + (!/^\d+$/u.test(declaredLength) || Number(declaredLength) > JSON_LIMIT) + ) { + throw new ApiError(413, 'request_too_large'); + } + if (request.body === null) { + throw new ApiError(400, 'invalid_json'); + } + + const reader = request.body.getReader(); + const chunks: Uint8Array[] = []; + let length = 0; + try { + while (true) { + const chunk = await reader.read(); + if (chunk.done) { + break; + } + length += chunk.value.byteLength; + if (length > JSON_LIMIT) { + await reader.cancel(); + throw new ApiError(413, 'request_too_large'); + } + chunks.push(chunk.value); + } + } finally { + reader.releaseLock(); + } + + const bytes = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + try { + return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); + } catch { + throw new ApiError(400, 'invalid_json'); + } +} + +function requireSameOriginMutation(request: Request): void { + const url = new URL(request.url); + if ( + url.origin !== IDENTITY_ISSUER || + request.headers.get('Origin') !== IDENTITY_ISSUER || + request.headers.get('Sec-Fetch-Site') !== 'same-origin' + ) { + throw new ApiError(403, 'cross_origin_denied'); + } +} + +async function fixedTimeEqual(first: string, second: string): Promise { + const encoder = new TextEncoder(); + const [firstDigest, secondDigest] = await Promise.all([ + crypto.subtle.digest('SHA-256', encoder.encode(first)), + crypto.subtle.digest('SHA-256', encoder.encode(second)), + ]); + const firstBytes = new Uint8Array(firstDigest); + const secondBytes = new Uint8Array(secondDigest); + let difference = 0; + for (let index = 0; index < firstBytes.length; index += 1) { + difference |= firstBytes[index]! ^ secondBytes[index]!; + } + return difference === 0; +} + +function parseSessionData(value: string): SessionData | null { + let parsed: unknown; + try { + parsed = JSON.parse(value); + } catch { + return null; + } + const csrfToken = + typeof parsed === 'object' && + parsed !== null && + 'csrfToken' in parsed && + typeof parsed.csrfToken === 'string' + ? parsed.csrfToken + : ''; + if ( + !isPlainObject(parsed) || + Object.keys(parsed).length !== SESSION_DATA_KEYS.size || + Object.keys(parsed).some((key) => !SESSION_DATA_KEYS.has(key)) || + parsed.version !== 1 || + !TOKEN_PATTERN.test(csrfToken) || + parsed.issuer !== IDENTITY_ISSUER || + typeof parsed.subject !== 'string' || + parsed.subject.length === 0 + ) { + return null; + } + return { + version: 1, + csrfToken, + issuer: IDENTITY_ISSUER, + subject: parsed.subject as PrincipalId, + }; +} + +async function invalidateSession( + rawSessionId: string, + options: SupportApiOptions, +): Promise { + try { + await options.sessions.destroy(rawSessionId); + } catch (error) { + options.logger.log('error', 'support.session_invalidation_cleanup_failed'); + throw error; + } + throw new InvalidatedSessionError(); +} + +async function authenticate( + request: Request, + options: SupportApiOptions, +): Promise { + const rawSessionId = cookieValue(request, SESSION_COOKIE); + if (rawSessionId === null) { + return null; + } + const record = await options.sessions.get(rawSessionId); + if (record === null) { + throw new InvalidatedSessionError(); + } + const data = parseSessionData(record.data); + if (data === null || data.subject !== record.principalId) { + return invalidateSession(rawSessionId, options); + } + + let claims: VerifiedIdentityClaims; + try { + claims = await options.identity.claimsFor(record.principalId); + } catch (error) { + const code = + typeof error === 'object' && error !== null && 'code' in error + ? (error as { readonly code?: unknown }).code + : undefined; + if (code === 'invalid_state' || code === 'not_found') { + return invalidateSession(rawSessionId, options); + } + throw error; + } + + let link: IdentityLinkKey; + try { + link = options.identityLinkFromClaims(claims); + } catch { + return invalidateSession(rawSessionId, options); + } + if ( + claims.emailVerified !== true || + link.issuer !== data.issuer || + link.subject !== data.subject + ) { + return invalidateSession(rawSessionId, options); + } + + const user = await options.identity.getUser(link.subject); + if ( + user === null || + user.principalId !== link.subject || + user.status !== 'active' || + user.emailVerified !== true + ) { + return invalidateSession(rawSessionId, options); + } + return { + rawSessionId, + csrfToken: data.csrfToken, + link, + user, + }; +} + +async function requireAuthentication( + request: Request, + options: SupportApiOptions, +): Promise { + const authenticated = await authenticate(request, options); + if (authenticated === null) { + throw new ApiError(401, 'authentication_required'); + } + return authenticated; +} + +async function requireCsrf( + request: Request, + authenticated: Authenticated, +): Promise { + const supplied = request.headers.get('X-Pegma-CSRF') ?? ''; + if ( + !TOKEN_PATTERN.test(supplied) || + !(await fixedTimeEqual(supplied, authenticated.csrfToken)) + ) { + throw new ApiError(403, 'csrf_denied'); + } +} + +async function enforceRateLimit( + limiter: DurableRateLimiter, + key: string, +): Promise { + const decision = await limiter.allow(key); + if (!decision.allowed) { + const retryAfterSeconds = + decision.retryAfter !== undefined && + Number.isFinite(decision.retryAfter) && + decision.retryAfter > 0 + ? Math.ceil(decision.retryAfter / 1_000) + : undefined; + throw new ApiError(429, 'rate_limited', retryAfterSeconds); + } +} + +function publicTicketSummary(ticket: CustomerTicketSummary) { + return { + id: ticket.id, + number: ticket.number, + subject: ticket.subject, + ...(ticket.category === undefined ? {} : { category: ticket.category }), + status: ticket.status, + channel: ticket.channel, + createdAt: ticket.createdAt, + customerUpdatedAt: ticket.customerUpdatedAt, + marker: pegSubjectMarker(ticket.number), + url: publicTicketUrl(ticket.id), + }; +} + +function publicTicketView(view: CustomerTicketView) { + return { + ticket: publicTicketSummary(view.ticket), + messages: view.messages.map((message) => ({ + 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 publicError(error: unknown): ApiError { + if (error instanceof ApiError) { + return error; + } + const mapped = mapSupportError(error); + return new ApiError( + mapped.status, + mapped.code, + mapped.retryAfterSeconds, + ); +} + +function parseCategory(value: unknown): PegmaSupportCategory { + if (typeof value !== 'string' || !PEGMA_SUPPORT_CATEGORY_SET.has(value)) { + throw new ApiError(400, 'invalid_category'); + } + return value as PegmaSupportCategory; +} + +/** + * Authenticated Support Desk customer 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. + */ +export function createSupportApi( + options: SupportApiOptions, +): (request: Request) => Promise { + return async (request) => { + const url = new URL(request.url); + const path = url.pathname; + try { + if (request.method === 'GET' && path === '/api/support/categories') { + // Categories are public configuration; list requires auth so the + // feedback form can only load them after sign-in. + const authenticated = await requireAuthentication(request, options); + return json({ + categories: [...PEGMA_SUPPORT_CATEGORIES], + csrfToken: authenticated.csrfToken, + }); + } + + if (request.method === 'GET' && path === '/api/support/tickets') { + const authenticated = await requireAuthentication(request, options); + const access = customerAccessContext(authenticated.link.subject); + const tickets = await options.application.listCustomerTickets(access); + return json({ + tickets: tickets.map(publicTicketSummary), + csrfToken: authenticated.csrfToken, + }); + } + + const ticketMatch = TICKET_ID_PATH.exec(path); + if ( + ticketMatch !== null && + ticketMatch[2] === undefined && + request.method === 'GET' + ) { + const ticketId = ticketMatch[1]!; + const authenticated = await requireAuthentication(request, options); + const access = customerAccessContext(authenticated.link.subject); + const view = await options.application.readCustomerTicket( + access, + ticketId, + ); + return json({ + ...publicTicketView(view), + csrfToken: authenticated.csrfToken, + }); + } + + if (request.method !== 'POST') { + throw new ApiError(404, 'not_found'); + } + requireSameOriginMutation(request); + + if (path === '/api/support/tickets') { + const authenticated = await requireAuthentication(request, options); + await requireCsrf(request, authenticated); + await enforceRateLimit( + options.createLimiter, + authenticated.link.subject, + ); + + const body = optionalKeysObject( + await readJson(request), + ['subject', 'body', 'category'], + [], + ); + const subject = boundedString(body.subject, 1, 200); + const messageBody = boundedString(body.body, 1, 20_000, { + allowMultiline: true, + }); + const category = parseCategory(body.category); + + const access = customerAccessContext(authenticated.link.subject); + const ticketId = mintSupportId(); + const messageId = mintSupportId(); + const commandId = mintSupportId(); + const correlationId = mintSupportId(); + + const view = await options.application.createCustomerTicket(access, { + commandId, + correlationId, + ticketId, + messageId, + subject, + body: messageBody, + category, + requesterEmail: authenticated.user.email, + }); + + options.logger.log('info', 'support.ticket_created', { + ticketNumber: view.ticket.number, + category, + }); + + return json(publicTicketView(view), { status: 201 }); + } + + if ( + ticketMatch !== null && + ticketMatch[2] === 'replies' && + request.method === 'POST' + ) { + const ticketId = ticketMatch[1]!; + const authenticated = await requireAuthentication(request, options); + await requireCsrf(request, authenticated); + await enforceRateLimit( + options.replyLimiter, + authenticated.link.subject, + ); + + const body = exactObject(await readJson(request), ['body']); + const messageBody = boundedString(body.body, 1, 20_000, { + allowMultiline: true, + }); + const access = customerAccessContext(authenticated.link.subject); + const view = await options.application.replyToCustomerTicket(access, { + commandId: mintSupportId(), + correlationId: mintSupportId(), + ticketId, + messageId: mintSupportId(), + body: messageBody, + }); + + options.logger.log('info', 'support.ticket_replied', { + ticketNumber: view.ticket.number, + }); + + return json(publicTicketView(view), { status: 201 }); + } + + throw new ApiError(404, 'not_found'); + } catch (error) { + const mapped = publicError(error); + if (mapped.status >= 500) { + options.logger.log('error', 'support.api_error', { + code: mapped.code, + error: error instanceof Error ? error.name : 'unknown', + }); + } else { + options.logger.log('info', 'support.api_rejected', { + code: mapped.code, + status: mapped.status, + }); + } + const headers: Record = {}; + if (mapped.retryAfterSeconds !== undefined) { + headers['Retry-After'] = String(mapped.retryAfterSeconds); + } + return json( + { error: mapped.code }, + { status: mapped.status, headers }, + ); + } + }; +} diff --git a/worker/src/support-cursors.ts b/worker/src/support-cursors.ts new file mode 100644 index 0000000..b6d6c45 --- /dev/null +++ b/worker/src/support-cursors.ts @@ -0,0 +1,80 @@ +import { + defineCollection, + type Store, + type StoredValue, +} from '@pegma/storage-core'; + +/** + * Host-owned Support Desk maintenance cursors. + * + * Independent of Identity mail cursors (`pegma-dev-maintenance`). Never share + * a cursor across loops or with Identity. Only queue loops persist cursors + * here; durable rate-limit sweeps are best-effort and do not keep host + * bookmarks. + */ +export type SupportCursorName = + | 'queueRepairCursor' + | 'queueInactiveSweepCursor'; + +interface SupportMaintenanceRecord { + readonly partition: StoredValue; + readonly id: StoredValue; + readonly queueRepairCursor: StoredValue; + readonly queueInactiveSweepCursor: StoredValue; +} + +const KEY = { partition: 'support-desk', id: 'maintenance' } as const; + +const maintenance = defineCollection({ + name: 'pegma-dev-support-maintenance', + key: (value) => ({ + partition: String(value.partition), + id: String(value.id), + }), + codec: { + encode: (value) => ({ ...value }), + decode: (record) => ({ + partition: record.partition ?? null, + id: record.id ?? null, + queueRepairCursor: record.queueRepairCursor ?? null, + queueInactiveSweepCursor: record.queueInactiveSweepCursor ?? null, + }), + }, +}); + +function cursor(value: StoredValue): string | undefined { + return typeof value === 'string' && value.length <= 8_192 ? value : undefined; +} + +function emptyRecord(): SupportMaintenanceRecord { + return { + partition: KEY.partition, + id: KEY.id, + queueRepairCursor: null, + queueInactiveSweepCursor: null, + }; +} + +export async function readSupportCursor( + store: Store, + name: SupportCursorName, +): Promise { + const record = await store.collection(maintenance).get(KEY); + return record === null ? undefined : cursor(record[name]); +} + +export async function saveSupportCursor( + store: Store, + name: SupportCursorName, + next: string | null, +): Promise { + await store.collection(maintenance).update(KEY, (current) => ({ + action: 'write', + value: { + ...(current ?? emptyRecord()), + partition: KEY.partition, + id: KEY.id, + [name]: next, + }, + })); +} diff --git a/worker/src/support-desk.d1.test.ts b/worker/src/support-desk.d1.test.ts new file mode 100644 index 0000000..d828031 --- /dev/null +++ b/worker/src/support-desk.d1.test.ts @@ -0,0 +1,215 @@ +import { env } from 'cloudflare:workers'; +import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity'; +import { createCloudflareD1Store } from '@pegma/storage-cloudflare-d1'; +import { createSessionStore } from '@pegma/sessions'; +import { fixedClock, type Logger, type PrincipalId } from '@pegma/spine'; +import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + IDENTITY_ISSUER, + SESSION_COOKIE, +} from './identity-api'; +import type { + IdentityPort, + IdentityUser, + VerifiedIdentityClaims, +} from './identity-contracts'; +import { createSupportApi } from './support-api'; +import { createSupportRuntime } from './support-desk'; + +declare global { + namespace Cloudflare { + interface Env { + IDENTITY_DB: D1Database; + } + } +} + +const logger: Logger = { log: vi.fn() }; +const clock = fixedClock('2026-07-29T15:00:00.000Z'); +const principalId = 'd1-principal' as PrincipalId; + +/** Semantically matches worker/migrations/0001_pegma_storage.sql. */ +const SCHEMA_STATEMENTS = [ + `CREATE TABLE IF NOT EXISTS RECORDS ( + partition_key TEXT NOT NULL, + row_key TEXT NOT NULL, + record_json TEXT, + version INTEGER NOT NULL, + deleted INTEGER NOT NULL CHECK (deleted IN (0, 1)), + PRIMARY KEY (partition_key, row_key) +) STRICT`, + `CREATE TABLE IF NOT EXISTS PEGMA_STORAGE_D1_TX_GUARD ( + reason TEXT NOT NULL +) STRICT`, + `CREATE TRIGGER IF NOT EXISTS PEGMA_STORAGE_D1_TX_ABORT_EXISTS +BEFORE INSERT ON PEGMA_STORAGE_D1_TX_GUARD +WHEN NEW.reason = 'exists' +BEGIN + SELECT RAISE(ABORT, 'PEGMA_STORAGE_D1_TX_EXISTS'); +END`, + `CREATE TRIGGER IF NOT EXISTS PEGMA_STORAGE_D1_TX_ABORT_MISSING +BEFORE INSERT ON PEGMA_STORAGE_D1_TX_GUARD +WHEN NEW.reason = 'missing' +BEGIN + SELECT RAISE(ABORT, 'PEGMA_STORAGE_D1_TX_MISSING'); +END`, + `CREATE TRIGGER IF NOT EXISTS PEGMA_STORAGE_D1_TX_ABORT_CHANGED +BEFORE INSERT ON PEGMA_STORAGE_D1_TX_GUARD +WHEN NEW.reason = 'changed' +BEGIN + SELECT RAISE(ABORT, 'PEGMA_STORAGE_D1_TX_CHANGED'); +END`, +] as const; + +beforeAll(async () => { + for (const statement of SCHEMA_STATEMENTS) { + await env.IDENTITY_DB.prepare(statement).run(); + } +}); + +beforeEach(async () => { + await env.IDENTITY_DB.prepare('DELETE FROM RECORDS').run(); + await env.IDENTITY_DB.prepare('DELETE FROM PEGMA_STORAGE_D1_TX_GUARD').run(); +}); + +function identity(): IdentityPort { + const user: IdentityUser = { + principalId, + email: 'd1@example.test', + emailVerified: true, + status: 'active', + createdAt: '2026-07-29T00:00:00.000Z', + updatedAt: '2026-07-29T00:00:00.000Z', + }; + return { + claimsFor: vi.fn(async () => + ({ + issuer: IDENTITY_ISSUER, + subject: principalId, + emailVerified: true, + }) satisfies VerifiedIdentityClaims, + ), + getUser: vi.fn(async () => user), + beginPasskeyRegistration: vi.fn(), + finishPasskeyRegistration: vi.fn(), + beginPasskeyAuthentication: vi.fn(), + finishPasskeyAuthentication: vi.fn(), + listPasskeys: vi.fn(async () => []), + removePasskey: vi.fn(async () => true), + }; +} + +describe('Support Desk over Cloudflare D1', () => { + it('proves create/list/read/reply with createSchemaIfMissing: false', async () => { + const store = createCloudflareD1Store({ + database: env.IDENTITY_DB, + createSchemaIfMissing: false, + }); + const sessions = createSessionStore(store, { logger }); + const id = identity(); + const runtime = createSupportRuntime({ + store, + sessions, + identity: id, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + logger, + clock, + }); + const api = createSupportApi({ + application: runtime.application, + sessions, + identity: id, + identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, + createLimiter: runtime.createLimiter, + replyLimiter: runtime.replyLimiter, + logger, + }); + + const sessionId = 'd'.repeat(43); + const csrfToken = 'e'.repeat(43); + await sessions.create(sessionId, { + principalId, + data: JSON.stringify({ + version: 1, + csrfToken, + issuer: IDENTITY_ISSUER, + subject: principalId, + }), + }); + const cookie = `${SESSION_COOKIE}=${sessionId}`; + + const created = await api( + new Request('https://pegma.dev/api/support/tickets', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Origin: IDENTITY_ISSUER, + 'Sec-Fetch-Site': 'same-origin', + Cookie: cookie, + 'X-Pegma-CSRF': csrfToken, + }, + body: JSON.stringify({ + subject: 'D1 feedback', + body: 'End-to-end against real D1 collections.', + category: 'feature_request', + }), + }), + ); + expect(created.status).toBe(201); + const createdBody = (await created.json()) as { + ticket: { id: string; number: number; marker: string }; + messages: readonly unknown[]; + }; + expect(createdBody.ticket.number).toBe(1); + expect(createdBody.ticket.marker).toBe('[PEG-1]'); + expect(createdBody.messages).toHaveLength(1); + + const listed = await api( + new Request('https://pegma.dev/api/support/tickets', { + headers: { Cookie: cookie }, + }), + ); + expect(listed.status).toBe(200); + const listBody = (await listed.json()) as { + tickets: readonly { id: string }[]; + }; + expect(listBody.tickets.map((ticket) => ticket.id)).toEqual([ + createdBody.ticket.id, + ]); + + const read = await api( + new Request( + `https://pegma.dev/api/support/tickets/${createdBody.ticket.id}`, + { headers: { Cookie: cookie } }, + ), + ); + expect(read.status).toBe(200); + + const reply = await api( + new Request( + `https://pegma.dev/api/support/tickets/${createdBody.ticket.id}/replies`, + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Origin: IDENTITY_ISSUER, + 'Sec-Fetch-Site': 'same-origin', + Cookie: cookie, + 'X-Pegma-CSRF': csrfToken, + }, + body: JSON.stringify({ body: 'Follow-up on D1 path.' }), + }, + ), + ); + expect(reply.status).toBe(201); + const replyBody = (await reply.json()) as { + messages: readonly unknown[]; + }; + expect(replyBody.messages).toHaveLength(2); + + const unauth = await api( + new Request('https://pegma.dev/api/support/tickets'), + ); + expect(unauth.status).toBe(401); + }); +}); diff --git a/worker/src/support-desk.ts b/worker/src/support-desk.ts new file mode 100644 index 0000000..83be4d7 --- /dev/null +++ b/worker/src/support-desk.ts @@ -0,0 +1,269 @@ +import { + createDurableLimiter, + defineRateLimitPolicy, + type DurableRateLimiter, +} from '@pegma/rate-limit'; +import { + systemClock, + type Clock, + type Logger, + type PrincipalId, +} from '@pegma/spine'; +import { createCloudflareD1Store } from '@pegma/storage-cloudflare-d1'; +import type { Store } from '@pegma/storage-core'; +import { + createSupportDeskApplication, + defaultQueueTerminalRetentionMilliseconds, + SupportDeskAuthorizationError, + SupportDeskConflictError, + SupportDeskLimitError, + SupportDeskNotFoundError, + SupportDeskQueueCapacityError, + ticketNumbers, + type SupportDeskApplication, +} from '@pegma/support-desk-application'; +import { defineTemplate } from '@pegma/support-desk-templates'; +import type { IdentityLinkProjector, IdentityPort } from './identity-contracts'; +import type { SessionStore } from '@pegma/sessions'; + +/** Host-configured category allowlist for pegma.dev product feedback. */ +export const PEGMA_SUPPORT_CATEGORIES = Object.freeze([ + 'feedback', + 'bug', + 'feature_request', + 'documentation', + 'question', +] as const); + +export type PegmaSupportCategory = (typeof PEGMA_SUPPORT_CATEGORIES)[number]; + +export const PEGMA_SUPPORT_CATEGORY_SET: ReadonlySet = new Set( + PEGMA_SUPPORT_CATEGORIES, +); + +/** Durable rate-limit policy names (separate from Identity). */ +export const SUPPORT_CREATE_LIMIT_POLICY = 'pegma.support.ticket.create'; +export const SUPPORT_REPLY_LIMIT_POLICY = 'pegma.support.ticket.reply'; + +export const SUPPORT_TERMINAL_RETENTION_MS = + defaultQueueTerminalRetentionMilliseconds; + +/** Public ticket URL on pegma.dev (own-ticket tracking page). */ +export function publicTicketUrl(ticketId: string): string { + return `https://pegma.dev/feedback/ticket/?id=${encodeURIComponent(ticketId)}`; +} + +/** Subject marker helpers: `[PEG-1042]`. */ +export function pegSubjectMarker(ticketNumber: number): string { + if (!Number.isSafeInteger(ticketNumber) || ticketNumber <= 0) { + throw new TypeError('ticketNumber must be a positive safe integer'); + } + return `[PEG-${ticketNumber}]`; +} + +export function formatPegmaTicketSubject( + ticketNumber: number, + subject: string, +): string { + return `${pegSubjectMarker(ticketNumber)} ${subject}`; +} + +/** Pegma-branded templates (available for later mail activation). */ +export const pegmaStaffNewTicketTemplate = defineTemplate({ + id: 'pegma.staff-new-ticket', + version: 1, + variables: ['ticket_number', 'subject'], + plainText: 'New pegma.dev feedback #{{ticket_number}}: {{subject}}', + html: '

New pegma.dev feedback #{{ticket_number}}: {{subject}}

', +}); + +export const pegmaCustomerReplyTemplate = defineTemplate({ + id: 'pegma.customer-reply', + version: 1, + variables: ['ticket_number', 'message_body', 'ticket_url'], + httpsUrlVariables: ['ticket_url'], + plainText: + 'Pegma replied to ticket #{{ticket_number}}.\n\n{{message_body}}\n\nView and reply: {{ticket_url}}', + html: '

Pegma replied to ticket #{{ticket_number}}.

{{message_body}}

View and reply

', +}); + +/** Server-minted opaque IDs for commands, tickets, and messages. */ +export function mintSupportId(): string { + return crypto.randomUUID(); +} + +export interface SupportErrorBody { + readonly error: string; +} + +/** + * Map Support Desk application outcomes to host HTTP status + stable code. + * Never include raw exception messages, storage keys, or conversation content. + */ +export function mapSupportError(error: unknown): { + readonly status: number; + readonly code: string; + readonly retryAfterSeconds?: number; +} { + if (error instanceof SupportDeskAuthorizationError) { + return { status: 403, code: 'forbidden' }; + } + if (error instanceof SupportDeskNotFoundError) { + // Missing and non-owned tickets share one content-free 404. + return { status: 404, code: 'not_found' }; + } + if (error instanceof SupportDeskConflictError) { + return { status: 409, code: 'conflict' }; + } + if (error instanceof SupportDeskQueueCapacityError) { + return { status: 503, code: 'queue_unavailable' }; + } + if (error instanceof SupportDeskLimitError) { + if (error.field === 'subject' || error.field === 'body') { + return { status: 413, code: 'payload_too_large' }; + } + return { status: 409, code: 'limit_exceeded' }; + } + if (error instanceof TypeError) { + return { status: 400, code: 'invalid_request' }; + } + if ( + typeof error === 'object' && + error !== null && + 'code' in error && + (error as { readonly code?: unknown }).code === 'rate_limited' + ) { + const retryAfter = + 'retryAfter' in error && + typeof (error as { readonly retryAfter?: unknown }).retryAfter === + 'number' && + Number.isFinite((error as { readonly retryAfter: number }).retryAfter) && + (error as { readonly retryAfter: number }).retryAfter > 0 + ? Math.ceil( + (error as { readonly retryAfter: number }).retryAfter / 1_000, + ) + : undefined; + return { status: 429, code: 'rate_limited', retryAfterSeconds: retryAfter }; + } + return { status: 500, code: 'internal_error' }; +} + +export interface SupportRuntimeEnv { + readonly IDENTITY_DB: D1Database; + /** When `"true"`, health includes a lightweight Support Desk store probe. */ + readonly SUPPORT_HEALTH_PROBE?: string; +} + +export interface SupportCompositionOptions { + readonly store: Store; + readonly sessions: SessionStore; + readonly identity: IdentityPort; + readonly identityLinkFromClaims: IdentityLinkProjector; + readonly logger: Logger; + readonly clock?: Clock; + readonly createLimiter?: DurableRateLimiter; + readonly replyLimiter?: DurableRateLimiter; +} + +export interface SupportRuntime { + readonly store: Store; + readonly application: SupportDeskApplication; + readonly clock: Clock; + readonly createLimiter: DurableRateLimiter; + readonly replyLimiter: DurableRateLimiter; + readonly limiters: readonly DurableRateLimiter[]; + readonly terminalRetentionMilliseconds: number; + readonly sessions: SessionStore; + readonly identity: IdentityPort; + readonly identityLinkFromClaims: IdentityLinkProjector; +} + +function durableLimiter( + store: Store, + name: string, + limit: number, + windowMs: number, + clock: Clock, +): DurableRateLimiter { + return createDurableLimiter( + defineRateLimitPolicy({ name, limit, windowMs }), + store, + { clock }, + ); +} + +/** + * Production Support Desk composition for pegma.dev. + * + * Uses the same `IDENTITY_DB` D1 binding with Support Desk's own collection + * names (`support-desk.*.v1`). Isolation is by collection, not by sharing + * Identity mail cursors or session row layouts. + */ +export function createProductionSupportRuntime( + env: SupportRuntimeEnv, + options: Omit, +): SupportRuntime { + const store = createCloudflareD1Store({ + database: env.IDENTITY_DB, + createSchemaIfMissing: false, + }); + return createSupportRuntime({ ...options, store }); +} + +/** Exact package composition with an injected conforming Store for tests. */ +export function createSupportRuntime( + options: SupportCompositionOptions, +): SupportRuntime { + const store = options.store; + const clock = options.clock ?? systemClock; + const createLimiter = + options.createLimiter ?? + durableLimiter(store, SUPPORT_CREATE_LIMIT_POLICY, 10, 60 * 60_000, clock); + const replyLimiter = + options.replyLimiter ?? + durableLimiter(store, SUPPORT_REPLY_LIMIT_POLICY, 30, 60 * 60_000, clock); + + const application = createSupportDeskApplication({ + store, + clock, + logger: options.logger, + allowedCategories: PEGMA_SUPPORT_CATEGORIES, + queueTerminalRetentionMilliseconds: SUPPORT_TERMINAL_RETENTION_MS, + }); + + return Object.freeze({ + store, + application, + clock, + createLimiter, + replyLimiter, + limiters: Object.freeze([createLimiter, replyLimiter]), + terminalRetentionMilliseconds: SUPPORT_TERMINAL_RETENTION_MS, + sessions: options.sessions, + identity: options.identity, + identityLinkFromClaims: options.identityLinkFromClaims, + }); +} + +/** Lightweight store probe for health — no ticket or message content. */ +export async function probeSupportStore(store: Store): Promise<{ + readonly ok: boolean; + readonly collections: 'support-desk'; +}> { + // Touch the ticket-number collection key path without reading message bodies. + // A get that returns null is success; thrown storage errors fail the probe. + await store.collection(ticketNumbers).get({ + partition: 'instance', + id: 'ticket-number', + }); + return { ok: true, collections: 'support-desk' }; +} + +export function supportHealthProbeEnabled(env: { + readonly SUPPORT_HEALTH_PROBE?: string; +}): boolean { + return String(env.SUPPORT_HEALTH_PROBE ?? '') === 'true'; +} + +/** Type-only re-export helper for principal branding at the host boundary. */ +export type SupportPrincipalId = PrincipalId; diff --git a/worker/src/support-maintenance.ts b/worker/src/support-maintenance.ts new file mode 100644 index 0000000..5eb9d22 --- /dev/null +++ b/worker/src/support-maintenance.ts @@ -0,0 +1,87 @@ +import { + repairQueueProjectionPage, + sweepInactiveQueueProjections, +} from '@pegma/support-desk-application'; +import type { DurableRateLimiter } from '@pegma/rate-limit'; +import type { Clock, Logger } from '@pegma/spine'; +import type { Store } from '@pegma/storage-core'; +import { readSupportCursor, saveSupportCursor } from './support-cursors'; +import { SUPPORT_TERMINAL_RETENTION_MS } from './support-desk'; + +export interface SupportMaintenanceRuntime { + readonly store: Store; + readonly clock: Clock; + readonly limiters: readonly DurableRateLimiter[]; + readonly terminalRetentionMilliseconds?: number; +} + +const PAGE_LIMIT = 50; + +async function runTask( + logger: Logger, + name: string, + task: () => Promise, +): Promise { + try { + await task(); + logger.log('info', 'support.maintenance_completed', { task: name }); + } catch (error) { + logger.log('error', 'support.maintenance_failed', { + task: name, + error: error instanceof Error ? error.name : 'unknown', + }); + } +} + +/** + * Host-owned Support Desk maintenance: queue repair, inactive sweep, and + * durable rate-limit window cleanup. Cursors are independent of Identity. + */ +export async function runSupportMaintenance( + runtime: SupportMaintenanceRuntime, + logger: Logger, +): Promise { + const terminalRetentionMilliseconds = + runtime.terminalRetentionMilliseconds ?? SUPPORT_TERMINAL_RETENTION_MS; + + const tasks: Promise[] = [ + runTask(logger, 'queue_repair', async () => { + const prior = await readSupportCursor(runtime.store, 'queueRepairCursor'); + const result = await repairQueueProjectionPage({ + store: runtime.store, + clock: runtime.clock, + terminalRetentionMilliseconds, + limit: PAGE_LIMIT, + ...(prior === undefined ? {} : { cursor: prior }), + }); + await saveSupportCursor( + runtime.store, + 'queueRepairCursor', + result.nextCursor, + ); + }), + runTask(logger, 'queue_inactive_sweep', async () => { + const prior = await readSupportCursor( + runtime.store, + 'queueInactiveSweepCursor', + ); + const result = await sweepInactiveQueueProjections({ + store: runtime.store, + clock: runtime.clock, + terminalRetentionMilliseconds, + limit: PAGE_LIMIT, + ...(prior === undefined ? {} : { cursor: prior }), + }); + await saveSupportCursor( + runtime.store, + 'queueInactiveSweepCursor', + result.nextCursor, + ); + }), + runTask(logger, 'rate_limits', async () => { + await Promise.all(runtime.limiters.map((limiter) => limiter.sweep())); + }), + ]; + + await Promise.all(tasks); +}