diff --git a/docs/SUPPORT_COMPOSITION.md b/docs/SUPPORT_COMPOSITION.md
index 5cfd842..de6ba63 100644
--- a/docs/SUPPORT_COMPOSITION.md
+++ b/docs/SUPPORT_COMPOSITION.md
@@ -146,10 +146,45 @@ with no default and styles the two modes differently. Mail / outbound
notification is still deferred (Task 10) — staff reply omits `notification`
like customer create/reply.
+### Role administration (`/api/admin/…`)
+
+Gated on the stored `Admin` role (`@pegma/authorization-admin`); the host
+checks permissions before calling the service, which never re-checks its own
+callers.
+
+| Method | Path | Notes |
+| --- | --- | --- |
+| `GET` | `/api/admin/state` | `bootstrapArmed` + CSRF token |
+| `POST` | `/api/admin/lookup` | One search box: body `{ query }`, resolves an email **or** a principal id |
+| `GET` | `/api/admin/principals/:id` | Principal + active roles with `managedBy` |
+| `GET` | `/api/admin/principals/:id/history` | Audited lifecycle timeline |
+| `POST` | `/api/admin/principals/:id/roles` | Assign `Support` or `Admin` |
+| `DELETE` | `/api/admin/assignments/:id` | Revoke; last-administrator guard |
+
+**One search box, decided server-side.** `classifyLookup` treats a `@`
+anywhere in the query as an email and everything else as a principal id:
+Identity's one normalization function requires exactly one `@` in every
+address, and principal ids never contain one. Email lookups call the
+published `Identity.findUserByEmail`; the host passes the trimmed value
+through **without normalizing it**, because exactly one normalization
+function exists and it lives in Identity (test-pinned).
+
+**Why the lookup is a POST.** The query can be a real person's email
+address, so it stays out of URLs, referrers, and access logs; the same
+choice puts CSRF and same-origin in front of the one endpoint that can
+confirm an address exists. Identity's public enumeration resistance is
+untouched — this path is reachable only by an authenticated `Admin` holder,
+and it is rate-limited so a stolen admin session cannot harvest the
+directory.
+
Durable rate-limit policies (separate from Identity):
- `pegma.support.ticket.create`
- `pegma.support.ticket.reply` (customer replies and staff message/note posts)
+- `pegma.admin.role.mutate` (assign / revoke, 30/h per operator)
+- `pegma.admin.principal.lookup` (directory lookups, 120/h per operator)
+
+All four are swept by the same scheduled maintenance run.
## Site pages
diff --git a/public/staff-roles.js b/public/staff-roles.js
index 968f9c7..1cb5a16 100644
--- a/public/staff-roles.js
+++ b/public/staff-roles.js
@@ -4,10 +4,11 @@ const forbidden = document.querySelector('#roles-forbidden');
const panel = document.querySelector('#roles-panel');
const bootstrapWarning = document.querySelector('#bootstrap-warning');
const lookupForm = document.querySelector('#lookup-form');
-const principalInput = document.querySelector('#lookup-principal');
+const lookupInput = document.querySelector('#lookup-query');
const principalCard = document.querySelector('#principal-card');
const principalEmail = document.querySelector('#principal-email');
const principalMeta = document.querySelector('#principal-meta');
+const principalMatched = document.querySelector('#principal-matched');
const roleList = document.querySelector('#role-list');
const assignForm = document.querySelector('#assign-form');
const assignRole = document.querySelector('#assign-role');
@@ -107,10 +108,11 @@ function renderRoles(roles) {
? 'Revoked — the guard restored the principal to keep an administrator.'
: 'Revoked.',
);
- await loadPrincipal(currentPrincipal);
+ await refreshPrincipal();
} catch (error) {
showStatus(
- MUTATION_ERRORS[error.message] ?? `Revoke failed (${error.message}).`,
+ MUTATION_ERRORS[error.message] ??
+ `Revoke failed (${error.message}).`,
true,
);
}
@@ -139,37 +141,84 @@ function renderHistory(events) {
}
}
-async function loadPrincipal(principalId) {
- const [detail, history] = await Promise.all([
- api(`/api/admin/principals/${encodeURIComponent(principalId)}`),
- api(`/api/admin/principals/${encodeURIComponent(principalId)}/history`),
- ]);
- currentPrincipal = principalId;
+function renderPrincipal(detail, matchedBy) {
+ currentPrincipal = detail.principal.principalId;
principalEmail.textContent = detail.principal.email;
principalMeta.textContent = `${detail.principal.principalId} · ${detail.principal.status} · created ${detail.principal.createdAt}`;
+ if (matchedBy === undefined) {
+ principalMatched.hidden = true;
+ } else {
+ principalMatched.textContent =
+ matchedBy === 'email'
+ ? 'Matched by email address.'
+ : 'Matched by principal id.';
+ principalMatched.hidden = false;
+ }
renderRoles(detail.roles);
- renderHistory(history.events);
principalCard.hidden = false;
}
+/**
+ * Every load takes a ticket. A second lookup (or a refresh after a
+ * mutation) invalidates any in-flight one, so a slow response can never
+ * paint its principal's history under a newer principal's details.
+ */
+let loadTicket = 0;
+
+/**
+ * Fetch details and history, then render BOTH or NEITHER: the card only
+ * becomes interactive once the pair belongs to the same principal.
+ */
+async function loadPrincipal(fetchDetail) {
+ const ticket = (loadTicket += 1);
+ const detail = await fetchDetail();
+ const id = encodeURIComponent(detail.principal.principalId);
+ const history = await api(`/api/admin/principals/${id}/history`);
+ if (ticket !== loadTicket) {
+ return;
+ }
+ renderPrincipal(detail, detail.matchedBy);
+ renderHistory(history.events);
+}
+
+/** One box: the worker decides email vs principal id. */
+async function resolvePrincipal(query) {
+ await loadPrincipal(() =>
+ api('/api/admin/lookup', {
+ method: 'POST',
+ body: JSON.stringify({ query }),
+ }),
+ );
+}
+
+/** Re-read the already-resolved principal after a mutation. */
+async function refreshPrincipal() {
+ const id = encodeURIComponent(currentPrincipal);
+ await loadPrincipal(() => api(`/api/admin/principals/${id}`));
+}
+
lookupForm.addEventListener('submit', async (event) => {
event.preventDefault();
- const principalId = principalInput.value.trim();
- if (principalId === '') {
+ const query = lookupInput.value.trim();
+ if (query === '') {
return;
}
- showStatus('Loading principal…');
+ showStatus('Looking up…');
try {
- await loadPrincipal(principalId);
+ await resolvePrincipal(query);
showStatus('Ready.');
} catch (error) {
principalCard.hidden = true;
- showStatus(
- error.status === 404
- ? 'No account with that principal id.'
- : `Lookup failed (${error.message}).`,
- true,
- );
+ if (error.status === 404) {
+ showStatus('No account matches that email or principal id.', true);
+ } else if (error.status === 400) {
+ showStatus(
+ 'That does not look like an email address or a principal id.',
+ true,
+ );
+ } else {
+ showStatus(`Lookup failed (${error.message}).`, true);
+ }
}
});
@@ -181,7 +230,9 @@ assignForm.addEventListener('submit', async (event) => {
const role = assignRole.value;
if (
role === 'Admin' &&
- !window.confirm('Grant the Admin role? Admins can change all role assignments.')
+ !window.confirm(
+ 'Grant the Admin role? Admins can change all role assignments.',
+ )
) {
return;
}
@@ -191,7 +242,7 @@ assignForm.addEventListener('submit', async (event) => {
{ method: 'POST', body: JSON.stringify({ role }) },
);
showStatus(`Assigned ${role}.`);
- await loadPrincipal(currentPrincipal);
+ await refreshPrincipal();
} catch (error) {
showStatus(
MUTATION_ERRORS[error.message] ?? `Assign failed (${error.message}).`,
diff --git a/src/pages/staff/roles.astro b/src/pages/staff/roles.astro
index 62aa43a..e0e91d7 100644
--- a/src/pages/staff/roles.astro
+++ b/src/pages/staff/roles.astro
@@ -48,27 +48,27 @@ import Base from '../../layouts/Base.astro';
+
Active roles
diff --git a/worker/src/admin-api.test.ts b/worker/src/admin-api.test.ts
index 9e4d493..19b43b9 100644
--- a/worker/src/admin-api.test.ts
+++ b/worker/src/admin-api.test.ts
@@ -3,7 +3,7 @@ import { createMemoryStore } from '@pegma/storage-core';
import { createSessionStore } from '@pegma/sessions';
import { fixedClock, type Logger, type PrincipalId } from '@pegma/spine';
import { describe, expect, it, vi } from 'vitest';
-import { createAdminApi } from './admin-api';
+import { classifyLookup, createAdminApi } from './admin-api';
import { IDENTITY_ISSUER, SESSION_COOKIE } from './identity-api';
import type {
IdentityPort,
@@ -13,6 +13,7 @@ import type {
import { createRoleHolderIndex } from './role-holder-index';
import { ADMIN_ROLE, SUPPORT_ROLE } from './support-access';
import {
+ createAdminLookupLimiter,
createAdminMutationLimiter,
createSupportRuntime,
} from './support-desk';
@@ -49,6 +50,12 @@ function identityFor(
emailVerified: true,
} satisfies VerifiedIdentityClaims;
}),
+ findUserByEmail: vi.fn(async (email: string) => {
+ for (const user of users.values()) {
+ if (user.email === email.trim().toLowerCase()) return user;
+ }
+ return null;
+ }),
getUser: vi.fn(
async (principalId: PrincipalId) => users.get(principalId) ?? null,
),
@@ -132,9 +139,10 @@ function fixture(options: { bootstrapPrincipals?: readonly PrincipalId[] } = {})
roleStore: runtime.roleStore,
holderIndex: createRoleHolderIndex(store),
mutationLimiter: createAdminMutationLimiter(store, clock),
+ lookupLimiter: createAdminLookupLimiter(store, clock),
bootstrapPrincipals: new Set(options.bootstrapPrincipals ?? []),
});
- return { api, sessions, roleStore: runtime.roleStore };
+ return { api, sessions, identity, roleStore: runtime.roleStore };
}
/** Seed the first administrator the way the bootstrap touch would. */
@@ -153,6 +161,126 @@ async function bootstrappedAdmin(
return { ...world, auth };
}
+describe('classifyLookup', () => {
+ it('routes anything containing @ to email and everything else to id', () => {
+ expect(classifyLookup('person@example.test')).toBe('email');
+ expect(classifyLookup('a41f406e-6e58-4090-b5b9-62bf7a8ab65d')).toBe(
+ 'principalId',
+ );
+ // Identity's normalization rejects malformed addresses; the classifier
+ // only decides which endpoint answers, never whether input is valid.
+ expect(classifyLookup('@')).toBe('email');
+ expect(classifyLookup('not-an-email')).toBe('principalId');
+ });
+});
+
+describe('one search box', () => {
+ it('resolves a principal id', async () => {
+ const { api, auth } = await bootstrappedAdmin();
+ const response = await api(
+ mutate('POST', '/api/admin/lookup', auth, { query: admin }),
+ );
+ expect(response.status).toBe(200);
+ const body = (await response.json()) as {
+ matchedBy: string;
+ principal: { principalId: string; email: string };
+ roles: readonly { role: string }[];
+ };
+ expect(body.matchedBy).toBe('principalId');
+ expect(body.principal.principalId).toBe(admin);
+ expect(body.roles.map((role) => role.role)).toEqual([ADMIN_ROLE]);
+ });
+
+ it('resolves an email and hands Identity the value verbatim', async () => {
+ const { api, auth, identity } = await bootstrappedAdmin();
+ const response = await api(
+ mutate('POST', '/api/admin/lookup', auth, {
+ query: ' Member@Example.TEST ',
+ }),
+ );
+ expect(response.status).toBe(200);
+ const body = (await response.json()) as {
+ matchedBy: string;
+ principal: { principalId: string };
+ };
+ expect(body.matchedBy).toBe('email');
+ expect(body.principal.principalId).toBe(member);
+ // Exactly one email normalization function exists and it lives in
+ // Identity: the host trims the text-box value and passes it through
+ // untouched — no host-side lowercasing.
+ expect(identity.findUserByEmail).toHaveBeenCalledWith('Member@Example.TEST');
+ });
+
+ it('answers 404 for an unknown principal and 400 for unusable input', async () => {
+ const { api, auth } = await bootstrappedAdmin();
+ expect(
+ (
+ await api(
+ mutate('POST', '/api/admin/lookup', auth, {
+ query: 'nobody@example.test',
+ }),
+ )
+ ).status,
+ ).toBe(404);
+ expect(
+ (await api(mutate('POST', '/api/admin/lookup', auth, { query: ' ' })))
+ .status,
+ ).toBe(400);
+ expect(
+ (
+ await api(
+ mutate('POST', '/api/admin/lookup', auth, {
+ query: `${'x'.repeat(320)}@example.test`,
+ }),
+ )
+ ).status,
+ ).toBe(400);
+ });
+
+ it('maps an Identity input rejection to 400, not 500', async () => {
+ const world = await bootstrappedAdmin();
+ world.identity.findUserByEmail = vi.fn(async () => {
+ throw Object.assign(new Error('bad'), { code: 'invalid_input' });
+ });
+ const response = await world.api(
+ mutate('POST', '/api/admin/lookup', world.auth, { query: 'a@b@c' }),
+ );
+ expect(response.status).toBe(400);
+ expect(await response.json()).toEqual({ error: 'invalid_query' });
+ });
+
+ it('is gated on the Admin role and CSRF like every other admin route', async () => {
+ const { api, sessions } = fixture();
+ const nobody = await sessionCookie(sessions, member, 'q'.repeat(43));
+ expect(
+ (
+ await api(
+ mutate(
+ 'POST',
+ '/api/admin/lookup',
+ { cookie: nobody.cookie, csrfToken: nobody.csrfToken },
+ { query: member },
+ ),
+ )
+ ).status,
+ ).toBe(403);
+
+ // A separate world: its session store owns the admin cookie below.
+ const bootstrapped = await bootstrappedAdmin();
+ const noCsrf = new Request('https://pegma.dev/api/admin/lookup', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Origin: IDENTITY_ISSUER,
+ 'Sec-Fetch-Site': 'same-origin',
+ Cookie: bootstrapped.auth.cookie,
+ },
+ body: JSON.stringify({ query: admin }),
+ });
+ expect((await bootstrapped.api(noCsrf)).status).toBe(403);
+ });
+});
+
describe('admin API access', () => {
it('requires authentication and the Admin role, fail-closed order', async () => {
const { api, sessions } = fixture();
diff --git a/worker/src/admin-api.ts b/worker/src/admin-api.ts
index ce3d98f..fa32a75 100644
--- a/worker/src/admin-api.ts
+++ b/worker/src/admin-api.ts
@@ -43,6 +43,22 @@ const PRINCIPAL_PATH =
/^\/api\/admin\/principals\/([A-Za-z0-9._~-]{1,200})(?:\/(roles|history))?$/u;
const ASSIGNMENT_PATH = /^\/api\/admin\/assignments\/([A-Za-z0-9._~-]{1,200})$/u;
+/** How a lookup query was interpreted. */
+export type LookupKind = 'email' | 'principalId';
+
+/**
+ * Decide whether an operator typed an email address or a principal id.
+ *
+ * `@` is a total, unambiguous discriminator here: Identity's one
+ * normalization function requires exactly one `@` in every email, and
+ * principal ids are opaque Identity subjects that never contain one (the
+ * principal route's own charset excludes it). One rule, server-side, so
+ * the operator gets a single search box instead of two.
+ */
+export function classifyLookup(query: string): LookupKind {
+ return query.includes('@') ? 'email' : 'principalId';
+}
+
/** The only roles the surface may assign; entitlements are not roles. */
const ASSIGNABLE_ROLES: ReadonlySet = Object.freeze(
new Set([SUPPORT_ROLE, ADMIN_ROLE]),
@@ -59,6 +75,12 @@ export interface AdminApiOptions {
readonly holderIndex: RoleHolderIndex;
/** Durable limiter for role mutations. */
readonly mutationLimiter: DurableRateLimiter;
+ /**
+ * Durable limiter for directory lookups. Separate from mutations: an
+ * authorized operator looks up far more often than they grant, and a
+ * stolen admin session must not be able to harvest the directory.
+ */
+ readonly lookupLimiter: DurableRateLimiter;
/**
* One-time Admin bootstrap principals (`PEGMA_ADMIN_BOOTSTRAP_PRINCIPALS`).
* Delete the var once the first administrator holds the role; the
@@ -180,6 +202,61 @@ export function createAdminApi(
});
}
+ // One search box: POST so the operator's query — which may be a real
+ // person's email — never lands in a URL, a referrer, or a log line,
+ // and so CSRF plus same-origin gate the one endpoint that can
+ // confirm an address exists.
+ if (request.method === 'POST' && path === '/api/admin/lookup') {
+ requireSameOriginMutation(request);
+ const authenticated = await requireAdminAccess(
+ request,
+ 'admin.principal.read',
+ );
+ await requireCsrf(request, authenticated);
+ await enforceRateLimit(
+ options.lookupLimiter,
+ authenticated.link.subject,
+ );
+ const body = exactObject(await readJson(request), ['query']);
+ const query =
+ typeof body.query === 'string' ? body.query.trim() : '';
+ if (query === '' || query.length > 320) {
+ throw new ApiError(400, 'invalid_query');
+ }
+ const matchedBy = classifyLookup(query);
+ let user;
+ try {
+ user =
+ matchedBy === 'email'
+ ? await options.identity.findUserByEmail(query)
+ : await options.identity.getUser(query as PrincipalId);
+ } catch (error) {
+ // Identity rejects malformed input; that is the operator's typo,
+ // not a server fault.
+ const code =
+ typeof error === 'object' && error !== null && 'code' in error
+ ? (error as { readonly code?: unknown }).code
+ : undefined;
+ if (code === 'invalid_input') {
+ throw new ApiError(400, 'invalid_query');
+ }
+ throw error;
+ }
+ if (user === null) {
+ throw new ApiError(404, 'not_found');
+ }
+ return json({
+ matchedBy,
+ principal: {
+ principalId: user.principalId,
+ email: user.email,
+ status: user.status,
+ createdAt: user.createdAt,
+ },
+ roles: await rolesView(administration, user.principalId),
+ });
+ }
+
const principalMatch = PRINCIPAL_PATH.exec(path);
if (principalMatch !== null) {
const principalId = principalMatch[1] as PrincipalId;
diff --git a/worker/src/identity-api.test.ts b/worker/src/identity-api.test.ts
index 36c2859..98ac2a3 100644
--- a/worker/src/identity-api.test.ts
+++ b/worker/src/identity-api.test.ts
@@ -70,6 +70,8 @@ class TestSessions implements SessionStore {
function identity(overrides: Partial = {}): IdentityPort {
return {
claimsFor: vi.fn(async () => claims),
+ findUserByEmail: vi.fn(async () => null),
+
getUser: vi.fn(async () => ({
principalId,
email: 'person@example.test',
diff --git a/worker/src/identity-contracts.ts b/worker/src/identity-contracts.ts
index 2cbedcc..d92238a 100644
--- a/worker/src/identity-contracts.ts
+++ b/worker/src/identity-contracts.ts
@@ -17,6 +17,7 @@ export type IdentityPort = Pick<
Identity,
| 'claimsFor'
| 'getUser'
+ | 'findUserByEmail'
| 'beginPasskeyRegistration'
| 'finishPasskeyRegistration'
| 'beginPasskeyAuthentication'
diff --git a/worker/src/index.ts b/worker/src/index.ts
index fd622f5..4eb6456 100644
--- a/worker/src/index.ts
+++ b/worker/src/index.ts
@@ -31,6 +31,7 @@ import { createAdminApi } from './admin-api';
import { createRoleHolderIndex } from './role-holder-index';
import { createSupportApi } from './support-api';
import {
+ createAdminLookupLimiter,
createAdminMutationLimiter,
createProductionSupportRuntime,
probeSupportStore,
@@ -78,6 +79,7 @@ function createSupportHandler(env: AppEnv, logger: ReturnType {
+ for (const user of users.values()) {
+ if (user.email === email.trim().toLowerCase()) return user;
+ }
+ return null;
+ }),
getUser: vi.fn(async (principalId: PrincipalId) => users.get(principalId) ?? null),
beginPasskeyRegistration: vi.fn(),
finishPasskeyRegistration: vi.fn(),
diff --git a/worker/src/support-desk.d1.test.ts b/worker/src/support-desk.d1.test.ts
index d828031..7062e25 100644
--- a/worker/src/support-desk.d1.test.ts
+++ b/worker/src/support-desk.d1.test.ts
@@ -89,6 +89,7 @@ function identity(): IdentityPort {
emailVerified: true,
}) satisfies VerifiedIdentityClaims,
),
+ findUserByEmail: vi.fn(async () => null),
getUser: vi.fn(async () => user),
beginPasskeyRegistration: vi.fn(),
finishPasskeyRegistration: vi.fn(),
diff --git a/worker/src/support-desk.ts b/worker/src/support-desk.ts
index 6bca8cf..e383f7c 100644
--- a/worker/src/support-desk.ts
+++ b/worker/src/support-desk.ts
@@ -223,6 +223,24 @@ export function createAdminMutationLimiter(
return durableLimiter(store, 'pegma.admin.role.mutate', 30, 60 * 60_000, clock);
}
+/**
+ * Durable limiter for role-administration directory lookups. Looser than
+ * the mutation limit — operators search far more than they grant — but
+ * bounded so a stolen admin session cannot harvest the directory.
+ */
+export function createAdminLookupLimiter(
+ store: Store,
+ clock: Clock = systemClock,
+): DurableRateLimiter {
+ return durableLimiter(
+ store,
+ 'pegma.admin.principal.lookup',
+ 120,
+ 60 * 60_000,
+ clock,
+ );
+}
+
/**
* Production Support Desk composition for pegma.dev.
*