Repository navigation
feat(labeler): serve the operator console and Access-guarded read API (W9.3 server) - #2015
Conversation
… (W9.3 server) Static assets under /admin with run_worker_first, and seven read-only /admin/api routes behind per-request Access verification with a reviewer role gate. Console client flips from fixtures to fetch. Claude-Session: https://claude.ai/code/session_014rikrGMh25h1rJczUQyTMM
… before worker The system-status route now reports disconnected instead of 500 when both the DO probe and the D1 fallback fail. Package build produces the console assets before the worker bundle so a clean deploy always has dist/console. Adds per-route unauthenticated-rejection coverage and full audit-field sanitization asserts. Claude-Session: https://claude.ai/code/session_014rikrGMh25h1rJczUQyTMM
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-demo-cache | 7ea2562 | Jul 13 2026, 12:54 PM |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-playground | 7ea2562 | Jul 13 2026, 12:53 PM |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-demo-do | 7ea2562 | Jul 13 2026, 12:54 PM |
Scope checkThis PR changes 2,015 lines across 19 files. Large PRs are harder to review and more likely to be closed without review. If this scope is intentional, no action needed. A maintainer will review it. If not, please consider splitting this into smaller PRs. See CONTRIBUTING.md for contribution guidelines. |
There was a problem hiding this comment.
This is the right change for W9.3: it serves the operator console from the labeler Worker, adds the Access-guarded read API, and switches the console client to live fetch. The architecture matches the approved RFC #694 and the design notes in the PR description. I didn’t run the test suite; this is a static review.
What I checked:
operator-read-guard.tscorrectly reuses the same-origin + CSRF asserts frommutation-guard.ts, verifies the Access JWT per request, and gates on thereviewerrole (with admin inheritance).console-api.tskeeps all reads behind the guard, returns{ data }/{ error: { code, message } }, rejects non-GET methods, never emits CORS headers, and clamps limits/cursors safely.assessment-store.tsadditions are parameterized (no SQL injection), include the needed indexes, and correctly computeisSupersededinline.console-serialize.tsexposes operator-only fields on findings while dropping the audit replay columns; tests assert that.- Tests cover unauthenticated rejection across all seven route families, role/CSRF/auth checks, cursor mismatch, sanitization, and method validation.
One concrete bug needs fixing before merge: the /admin static-asset branch forwards the original request path to the asset binding, but Vite’s base: "/admin/" only changes the public URLs in the built HTML, not the file-system layout. The asset binding will therefore look for dist/console/admin/assets/..., fall back to index.html, and the console JS/CSS won’t execute. The fix is to strip the /admin prefix before calling env.ASSETS.fetch.
Everything else is solid. I also noted the documented i18n exception for the labeler console and did not file hard-coded English strings as findings.
| // request regardless (see console-api.ts / operator-read-guard.ts). | ||
| if (pathname === "/admin/api" || pathname.startsWith("/admin/api/")) | ||
| return handleConsoleApiRequest(env, request, config); | ||
| if (pathname === "/admin" || pathname.startsWith("/admin/")) return env.ASSETS.fetch(request); |
There was a problem hiding this comment.
[needs fixing] The Worker forwards /admin/* directly to env.ASSETS.fetch(request). The asset binding maps request paths one-to-one into ./dist/console, but console/vite.config.ts sets base: "/admin/", so the built index.html references assets at /admin/assets/... while the actual files live at dist/console/assets/.... The binding therefore looks for dist/console/admin/assets/..., fails, and the SPA fallback returns index.html for JS/CSS requests — the console shell loads but cannot run its bundle.
Fix by stripping the /admin path prefix before serving assets, so /admin/assets/... maps to dist/console/assets/... and deep links fall back to the SPA shell correctly.
| if (pathname === "/admin" || pathname.startsWith("/admin/")) return env.ASSETS.fetch(request); | |
| if (pathname === "/admin" || pathname.startsWith("/admin/")) { | |
| const url = new URL(request.url); | |
| url.pathname = url.pathname.slice("/admin".length) || "/"; | |
| return env.ASSETS.fetch(new Request(url, request)); | |
| } |
There was a problem hiding this comment.
Applied in 7ea2562 — /admin requests are now rewritten through an exported pure helper (consoleAssetPath) before env.ASSETS.fetch, so /admin/assets/* resolves to dist/console/assets/* and deep links strip to non-file paths that hit the SPA fallback correctly. The helper uses the same prefix predicate as the dispatch (so /adminx still 404s) and excludes /admin/api* itself, making the api-vs-assets separation independent of branch order. 17 unit tests pin the rewrite matrix incl. the API exclusion; live asset serving stays on the W9.7 e2e list.
~ 🤖 Fable
The console builds with base /admin/ but the assets binding maps paths one-to-one into dist/console, so JS/CSS requests fell through to the SPA fallback and the shell never booted. API paths are excluded from the rewrite in the helper itself, independent of dispatch order. Claude-Session: https://claude.ai/code/session_014rikrGMh25h1rJczUQyTMM
|
Overlapping PRsThis PR modifies files that are also changed by other open PRs:
This may cause merge conflicts or duplicated work. A maintainer will coordinate. |
There was a problem hiding this comment.
Re-review of #2015. My prior review's single blocking bug is fixed: the /admin static-asset branch now strips the prefix via the new consoleAssetPath helper before calling env.ASSETS.fetch, so the SPA's base: "/admin/" hashed assets (/admin/assets/*) resolve to dist/console/assets/* instead of falling through to the shell. The helper is unit-tested across root/deep-link mappings, near-miss-prefix exclusions, and explicit /admin/api/* exclusion so an asset rewrite can never swallow an API path. index.ts dispatches /admin/api/* before the asset branch and forwards the rewritten URL with the original request's method/headers — correct for GET asset requests, and run_worker_first: true keeps the public XRPC/well-known/404 surface unchanged.
What I re-verified on this pass:
consoleAssetPath(apps/labeler/src/console-api.ts):/adminand/admin/→/;/admin/assets/x.js→/assets/x.js;/admin/api*→ null (API dispatched earlier); encoded-slash (/admin/api%2F…) and case (/Admin/…) variants fall to the asset SPA fallback, never to the API — no guard bypass.probeJetstreamConnected: the DO/statusreturns{ cursor, consecutiveFailures }and0⇒ connected matchesdiscovery-do.ts; the D1 freshness fallback queriesingest_statewithsource = 'jetstream'anddatetime('now','-15 minutes'), which matches thedatetime('now')write format used indiscovery-do.ts(and the aggregator precedent) — the lexicographic comparison is correct, not an ISO/T-separator mismatch. Both signal paths degrade tofalseon failure rather than throwing the status route.- Assessment-store additions (
getAssessmentsForUri,getFindingsForAssessment,getAllLabelsForAssessment,getCurrentSubjectByUri,countInFlightAssessments) are parameterized, select columns that exist against the migrations, and the label negation mapping isneg === 1.parseEvidenceRefsdegrades malformed JSON to[]. - Audit-log keyset (
getOperatorActionsPage) and serializer drop the five internal columns; columns/index match migration 0004. The two-filterless-endpoint cursor cross-usability noted in the PR description is acknowledged, reviewer-gated, keyset-only, and has no security impact — not a finding. - Console client switched to
createFetchClientwithcredentials: "same-origin"and theX-EmDash-RequestCSRF header;createFixtureClientstays exported for tests.
This is the right change for W9.3, matches RFC #694, and the one issue from the first review is resolved cleanly. Nothing new to fix. (Static review only — I did not run the suite.)
There was a problem hiding this comment.
Re-review of W9.3. My previous blocking finding — the /admin static-asset branch forwarded the original request path to env.ASSETS.fetch, so Vite's base: "/admin/" URLs would miss the binding and the shell would never execute — is fixed. consoleAssetPath now strips the /admin prefix (mapping /admin → /, /admin/assets/foo.js → /assets/foo.js, deep links → the SPA fallback), and it's covered by direct unit tests for rewrites, near-miss prefixes, and API-path exclusion. index.ts dispatches /admin/api/* before the asset branch and forwards only the rewritten path. I didn't run the suite; this is static.
What I verified this pass:
- Guard (
operator-read-guard.ts): reusesassertSameOrigin/assertCsrfHeaderfrommutation-guard.ts, runs a freshverifyAccessRequestper request, thenhasRole(..., "reviewer")with admin inheritance;AccessAuthError→UNAUTHENTICATED(401). Errors render via the shared{ error: { code, message } }shape. - Dispatcher (
console-api.ts):guardReadruns once at the top before any store read; non-GET →METHOD_NOT_ALLOWED(405) after the guard; unknown sub-paths →NOT_FOUND; cursors are keyset-validated and filter-hash-scoped;limitclamped to[1, 100]and rejects non-numbers;cache-control: no-storeand no CORS allow-origin header. Subject-URI segment is percent-decoded in a try/catch. - Routing/asset robustness:
new URLnormalizes..; encoded slashes (/admin%2fapi/...) don't match the literal/admin/apiprefix and fall through to 404; case variants don't match the console branch. No API bypass path found. - Store (
assessment-store.ts,operator-actions.ts): all new queries are parameterized;getAssessmentthrowsTypeErroron a malformed ULID and the detail route maps that toNOT_FOUND;SUPERSEDED_EXISTS_SQLis reused consistently;getOperatorActionsPagekeyset uses the existingidx_operator_actions_createdindex;ingest_state.updated_atis written withdatetime('now'), so the freshness-fallback comparison againstdatetime('now','-15 minutes')is format-consistent (theT-vs-space mismatch I suspected does not occur). Config-parse failure fails closed (500NOT_CONFIGURED); the cache only stores on success. - Serializers: operator surface keeps
privateDetail/evidenceRefs/modelId/promptHashand label negations; the audit view drops all five internal replay columns; tests assert both. - i18n / changeset: the labeler console's non-localization is a documented decision (2026-07-13), and
apps/labeleris private/unpublished, so no changeset is required — both consistent with the prior review's stance.
The documented informational note about two filterless endpoints sharing a cursor filter hash is reviewer-gated, keyset-only, and has no security impact — not a finding.
Headline: the prior blocker is resolved and the rest is solid. Approving with one minor suggestion below.
| * which the Queues API does not expose to the consumer Worker (spec §11.1's | ||
| * `/admin/system` "queue/DLQ health"). */ | ||
| async function countDeadLetters(db: D1Database): Promise<number> { | ||
| const row = await db.prepare(`SELECT COUNT(*) AS n FROM dead_letters`).first<{ n: number }>(); |
There was a problem hiding this comment.
[suggestion] countDeadLetters runs SELECT COUNT(*) FROM dead_letters, but dead_letters is an append-only table (no DELETE anywhere in the codebase — drainDiscoveryDeadLetterBatch writes a row and acks the queue message). So this value is the cumulative count of every record ever dead-lettered, not a current backlog. The field is named deadLetterDepth and the dashboard labels it "Dead-letter depth", which reads as a current gauge — an operator seeing 500 might assume 500 are stuck, when they're just historical. This is a deliberate, documented stand-in (the Queues API doesn't expose DLQ depth to the consumer Worker), so it isn't a bug, but either a comment/UI subtitle clarifying that it's cumulative-ever, or a received_at-windowed count, would make the metric honest.
| const row = await db.prepare(`SELECT COUNT(*) AS n FROM dead_letters`).first<{ n: number }>(); | |
| const row = await db | |
| .prepare(`SELECT COUNT(*) AS n FROM dead_letters`) // append-only table: cumulative count, not a current backlog | |
| .first<{ n: number }>(); |
943b254
into
feat/plugin-registry-labelling-service
What does this PR do?
Completes plan item W9.3: the labeler Worker now serves the operator console as static assets under
/adminand exposes the seven Access-guarded read-only/admin/api/*routes it consumes. The console client flips from fixtures to live fetch — the one-line swap the scaffold (#2006) was designed around.Serving: wrangler
assetsbinding over./dist/consolewithnot_found_handling: "single-page-application"andrun_worker_first: true— the Worker owns all routing, so the public XRPC/well-known/404 surface is dispatch-identical to before (the array-form SPA fallback would have shadowed public 404s with the console shell). The SPA shell itself carries no data; Cloudflare Access at the edge covers/admin/*as a deployment requirement, and every API request is independently verified in-Worker regardless.Read guard (
operator-read-guard.ts): same-origin andX-EmDash-Requestchecks (shared with the W9.2 mutation guard's exported helpers), then a freshverifyAccessRequestper request and areviewerrole gate (admin inherits) — all before route matching or any store read. GET-only (405 otherwise); errors use the{ error: { code, message } }wire shape; missing or malformedOPERATOR_ACCESS_CONFIGfails closed.Routes: assessments list (state filter, keyset cursor shared with the public list), assessment detail (404 → client renders not-found), findings, labels (incl. negations), subject history, audit log, system status. Serializers whitelist fields — the operator surface deliberately includes findings'
privateDetail/evidenceRefs(spec §13.2's exclusions govern public routes), while the audit view omits all five internal columns (idempotency_key,request_fingerprint,result_json,metadata_json, epoch sibling). System status reports only observable facts: jetstream connectivity (DO probe with a D1 freshness fallback that degrades to "disconnected" on store failure rather than failing the route), in-flight assessment count, and dead-letter depth.Client updates ratified against the design's open questions: the provisional
OperatorActiontype is replaced by the real audit shape (actor is the Accesssub; no DID), the dashboard metric isdeadLetterDepth(grounded in thedead_letterstable), andlastReconciliationAtis dropped from V1 rather than shipped as a null stub.pnpm buildnow produces the console before the worker bundle so a clean deploy always hasdist/console;deployruns the full build.Adversarially reviewed by an independent Opus pass focused on unauthenticated reach (path normalization, encoded slashes, case tricks), public-surface regression, serialization boundaries, cursor safety, and fail-closed config: no exploitable hole; its hardening (probe degradation, per-route unauthenticated-rejection tests across all seven route families, full audit sanitization asserts) is included. One informational note it raised, not addressed: pagination cursors for two filterless endpoints share a filter hash, so a cursor is technically cross-usable between them — both are reviewer-gated and keyset-only, no security impact; per-endpoint namespacing can tidy it later.
Deploy-time prerequisites (not code): a Cloudflare Access application policy must cover
/admin/*, andOPERATOR_ACCESS_CONFIG.audienceships as a placeholder that must be set to the real Access-app AUD tag. Static-asset serving and SPA deep-links are exercised by W9.7's e2e pass, not unit tests.Stacked on #2006. Targets
feat/plugin-registry-labelling-service. Related to #1909 and RFC #694.Type of change
Checklist
pnpm typecheckpassespnpm lintpassespnpm testpasses (or targeted tests for my change)pnpm formathas been runmessages.pochanges except in translation PRs — a workflow extracts catalogs on merge tomain.i18n n/a — no admin UI; the labeler console is deliberately not localized (decision 2026-07-13). Changeset n/a —
apps/labeleris a private, unpublished Worker app.AI-generated code disclosure
Screenshots / test output
pnpm --filter @emdash-cms/labeler test: worker 401 pass (24 files — new suites for the read guard, the seven-route dispatcher incl. per-route unauthenticated rejection and 405s, and serializer sanitization), console 9 passconsole:buildand a clean-treepnpm buildproducedist/console+ the worker bundle; lint: 0 diagnostics inapps/labelerfiles (one pre-existing repo diagnostic fixed in passing where the reviewed file tripped it)https://claude.ai/code/session_014rikrGMh25h1rJczUQyTMM
Try this PR
Open a fresh playground →
A full working EmDash site, deployed from this branch. Each visit gets its own session-scoped sandbox: no login needed and no shared state. Try the admin, edit content, hit the public site.
Tracks
feat/labeler-console-server. Updated automatically when the playground redeploys.