Skip to content

fix: redirect to setup wizard on fresh deployments - #8

Merged
ascorbic merged 1 commit into
mainfrom
fix/fresh-deploy-setup-redirect
Apr 1, 2026
Merged

ascorbic merged 1 commit into
mainfrom
fix/fresh-deploy-setup-redirect

Conversation

@ascorbic

@ascorbic ascorbic commented Apr 1, 2026

Copy link
Copy Markdown
Member

Summary

  • Fix crash on fresh CF deployments when the first request hits a public page before admin setup. The middleware fast-path skips runtime init (no migrations), but template helpers like getSiteSettings() still query the DB via getDb(), crashing with D1_ERROR: no such table: options.
  • Added a one-time setup probe in the middleware fast-path: checks if _emdash_migrations exists, redirects to setup wizard if not. Cached for the worker lifetime after first success -- zero ongoing cost.
  • Release workflow: switch to GitHub App token for changeset PRs.
  • Admin branding changeset (unrelated, bundled).

How it works

The main middleware has a fast-path for unauthenticated public page requests that skips the heavy CMS runtime init. On a fresh database this meant no migrations ran, but page templates still called getSiteSettings() -> getDb() -> queried missing tables.

Now, before the fast-path returns, a setupVerified flag is checked. On first request it probes the migrations table via the same getDb() instance the page will use. If the table doesn't exist, it redirects to /_emdash/admin/setup. The flag is also set to true when the full runtime init succeeds (admin/API requests), so the probe is skipped entirely if those run first.

Testing

  • Lint clean (pnpm lint:quick)
  • Typecheck clean (pnpm typecheck)

…s first request

On a fresh CF deployment, if the first request hits a public page, the
middleware fast-path skips runtime init. Template helpers like
getSiteSettings() then query an empty database and crash with
'no such table: options'.

Add a one-time setup probe in the middleware fast-path: check if the
migrations table exists, and redirect to the setup wizard if not.
The check is cached for the worker lifetime after first success.

Also includes release workflow update to use GitHub App token and
admin branding changeset.
@pkg-pr-new

pkg-pr-new Bot commented Apr 1, 2026

Copy link
Copy Markdown

Open in StackBlitz

@emdash-cms/admin

npm i https://pkg.pr.new/@emdash-cms/admin@8

@emdash-cms/auth

npm i https://pkg.pr.new/@emdash-cms/auth@8

@emdash-cms/blocks

npm i https://pkg.pr.new/@emdash-cms/blocks@8

@emdash-cms/cloudflare

npm i https://pkg.pr.new/@emdash-cms/cloudflare@8

emdash

npm i https://pkg.pr.new/emdash@8

create-emdash

npm i https://pkg.pr.new/create-emdash@8

@emdash-cms/gutenberg-to-portable-text

npm i https://pkg.pr.new/@emdash-cms/gutenberg-to-portable-text@8

@emdash-cms/x402

npm i https://pkg.pr.new/@emdash-cms/x402@8

@emdash-cms/plugin-ai-moderation

npm i https://pkg.pr.new/@emdash-cms/plugin-ai-moderation@8

@emdash-cms/plugin-atproto

npm i https://pkg.pr.new/@emdash-cms/plugin-atproto@8

@emdash-cms/plugin-audit-log

npm i https://pkg.pr.new/@emdash-cms/plugin-audit-log@8

@emdash-cms/plugin-color

npm i https://pkg.pr.new/@emdash-cms/plugin-color@8

@emdash-cms/plugin-embeds

npm i https://pkg.pr.new/@emdash-cms/plugin-embeds@8

@emdash-cms/plugin-forms

npm i https://pkg.pr.new/@emdash-cms/plugin-forms@8

@emdash-cms/plugin-webhook-notifier

npm i https://pkg.pr.new/@emdash-cms/plugin-webhook-notifier@8

commit: 3c319ed

@ascorbic
ascorbic merged commit 025a897 into main Apr 1, 2026
17 checks passed
travisbreaks pushed a commit to travisbreaks/emdash that referenced this pull request Apr 5, 2026
…p-redirect

fix: redirect to setup wizard on fresh deployments
ascorbic added a commit that referenced this pull request May 10, 2026
* feat(aggregator): DID resolver with known_publishers cache

First piece of the records-consumer slice.

Schema additions to 0001_init.sql (still pre-deploy, no follow-up
migration needed):
- publishers + publisher_verifications for the publisher.* NSIDs
- dead_letters for verification-failure forensics (distinct from
  the configured Cloudflare DLQ, which is for transient retry
  exhaustion — different failure modes, different destinations)
- signing_key / signing_key_id columns on known_publishers so the
  table doubles as the DID-doc resolution cache; 24h TTL applied
  at query time

WANTED_COLLECTIONS extended with publisher.profile and
publisher.verification.

DidResolver: pure constructor-injected class with a DidDocCache
interface (Map-backed in tests, known_publishers-backed in prod via
createD1DidDocCache). Materialises cached multibase keys to PublicKey
instances via @atcute/crypto, exhaustive on the p256/secp256k1
discriminated union. invalidate() for the re-resolve-after-key-rotation
path the verification step needs.

14 tests covering cache hit/miss/expiry/invalidate, malformed-DID
rejection, missing PDS / missing #atproto verification method
rejection, and the D1 binding contract (round-trip, first_seen_at
preserved across updates, end-to-end with the resolver).

* feat(aggregator): records consumer with PDS-verified ingest

Replaces the no-op queue() handler in index.ts with the full verification
+ ingest pipeline for the four record collections in scope (package.profile,
package.release, publisher.profile, publisher.verification).

Per-job pipeline:
1. Resolve PDS endpoint + signing key via DidResolver (cached in
   known_publishers, 24h TTL).
2. Fetch CAR via com.atproto.sync.getRecord, hand to @atcute/repo's
   verifyRecord (MST + signature in one call), capture carBytes for
   record_blob storage.
3. Cross-check verified vs Jetstream-supplied bytes; verified always
   wins; mismatch logs as `[aggregator] jetstream-discrepancy` for
   future Jetstream-correctness monitoring.
4. Lexicon-validate via @atcute/lexicons safeParse against the schema
   from @emdash-cms/registry-lexicons.
5. Per-collection structural checks:
   - package.profile: record.id must equal at://did/collection/rkey
     (the publisher could lie in the body even though MST verifies);
     slug optional, falls back to rkey, must match rkey if present
   - package.release: rkey must equal `<package>:<encoded-version>`,
     version must parse as semver, version_sort computed from a 10-digit
     zero-padded major.minor.patch + prerelease fragment
   - publisher.profile: rkey must be 'self'; contact entries must have
     at least one of url/email (lexicon can't express that constraint)
   - publisher.verification: facts stored as observed; validity check
     (current handle/displayName matches bound values) is read-time
6. Write to D1 with upserts on the appropriate primary key. Releases
   use INSERT … DO NOTHING; on a different-content same-version retry,
   audit a release_duplicate_attempts row with reason IMMUTABLE_VERSION.

Delete handling:
- Hard-delete for one-per-DID rows (package.profile, publisher.profile)
- Soft-delete (tombstoned_at) for everything else
- 0001_init.sql: releases FK now ON DELETE CASCADE so an out-of-order
  delete (publisher deletes profile before releases drain) doesn't get
  blocked by FK violation; the publisher's intent is the whole package
  going away

Error policy:
- PDS network/timeout/5xx: message.retry()
- 404, oversized response, signature/MST/lexicon failure, structural
  failure: write dead_letters row with structured reason + payload,
  message.ack(). Never retry — these are malicious or broken upstream
  and we know retrying won't help
- Unexpected programming errors: log loud, dead-letters, ack — never
  crash the worker (would block the queue slot)

Test coverage (37 new tests, 65 aggregator tests total):
- Per-collection writers: insert, upsert, lexicon failure, structural
  rejection (RKEY_MISMATCH, CONTACT_VALIDATION_FAILED, INVALID_VERSION)
- Releases: version_sort computation; same-content replay is silent;
  different-content replay audits release_duplicate_attempts
- Delete: hard-delete vs tombstone per collection; verification
  upsert clears tombstone (re-publish recovers)
- Dispatcher: ack on success, retry on transient PDS error, retry on
  network error, ack+dead_letters on permanent PDS error, delete
  short-circuits PDS fetch

Known gaps (deferred):
- End-to-end happy-path test using FakePublisher + MockPds requires a
  node-pool vitest project; left for a follow-up. Each layer is
  independently tested; the wiring between them is the gap.
- releases.cts column mirrors verified_at because the lexicon doesn't
  expose a creation timestamp and verifyRecord doesn't surface the
  commit rev. Tracked in the writer with a TODO.
- Slice 3 artifact-mirror enqueue is a TODO comment in the release
  writer; mirrored_artifacts stays empty for now.

* fix(aggregator): adversarial review fixes for records consumer

Address findings from the adversarial review of the records consumer
slice. Per-finding rationale:

BLOCKERS / CORRECTNESS

- B1: refreshPackageLatest() recomputes packages.latest_version +
  capabilities after release insert / un-tombstone / tombstone-on-delete.
  Before: profile writer bound `null` for both columns with a comment
  promising the release writer would populate them; release writer never
  did. Read APIs that read latest_version got NULL forever.

- B2: same-content release on a tombstoned row clears tombstoned_at
  instead of silently no-op'ing through DO NOTHING. Otherwise a
  delete-then-republish-same-content round-trip leaves the release
  invisible to readers with no audit row to explain why.

- B3: release.extensions field is now validated as a plain object
  containing a releaseExtension-keyed entry that passes
  PackageReleaseExtension.mainSchema. emdash_extension column stores
  only the validated payload (not arbitrary record.extensions).
  Previously the consumer wrote whatever the publisher sent, including
  scalars like "lol" — read API parsing would have thrown.

- M1: package.profile.security[] entries enforce "at least one of
  url|email" per lexicon. Was only enforced for publisher.profile.

- Mi7: release writer pre-checks parent profile existence and throws
  the new MissingDependencyError → controller.retry() instead of
  letting the FK violation bubble up as UNEXPECTED_ERROR with no
  recovery path. Out-of-order Jetstream delivery (release event before
  its profile event) now retries until the profile arrives or hits
  max_retries → DLQ for the reconciliation pass.

SHOULD-FIX / SAFETY

- M3: version_sort rejects components or prerelease numerics longer
  than 10 digits as INVALID_VERSION (the pad-width ceiling).

- M5/M6/N1: mapPdsReason parameter typed via the imported
  VerificationFailureReason union so a new reason added in
  pds-verify.ts becomes a compile-time error here. PDS_NETWORK_ERROR
  (the unreachable transient case) now throws "unreachable" instead
  of silently dead-lettering as UNEXPECTED_ERROR. Exhaustive `never`
  default catches future variants.

- M9: removed JSON.stringify discrepancy comparison between Jetstream
  copy and verified PDS copy. The verified copy always wins so the
  comparison is a monitoring signal only, but JSON.stringify isn't
  canonical (key order, undefined-vs-missing) so it would fire
  false-positive warnings constantly in real traffic. Add a
  CBOR-canonical comparator when this monitoring becomes load-bearing.

- M2 (piggybacked): applyDelete for releases parses rkey to use the
  PK index instead of the partial idx_releases_latest seek-then-scan.

- Mi5: applyDelete for unknown collections throws IngestError
  UNKNOWN_COLLECTION instead of silently warning + acking. The
  dispatcher's delete branch catches IngestError → forensics + ack so
  unknown collections land in dead_letters instead of disappearing.

- Mi6: record.package field validated against the package-slug regex
  (`^[a-zA-Z][a-zA-Z0-9_-]*$`). Closes the ambiguous-rkey hole where
  package="foo:bar" + version="1.0.0" produced the same rkey as
  package="foo" + version="bar:1.0.0".

- B4: processBatch accepts an optional depsOverride parameter for
  testability. Production wiring path is now unit-test reachable.

LINT / CODE QUALITY

- jetstream-client.ts: replaced `event as unknown as
  JetstreamCommitEvent` with a type-predicate `isCommitEvent` so the
  narrowing is explicit. Same runtime semantics.

- records-do.ts: dropped redundant `<Env>` type argument on
  `extends DurableObject` — `Cloudflare.Env` is the default.

- records-consumer.ts: introduced isPlainObject() type guard;
  dropped redundant constructor on MissingDependencyError.

REVIEW FINDINGS NOT FIXED

- M4 (DID syntax allowing underscore): phantom finding. The original
  regex already allowed `_` everywhere — the reviewer misread the
  character class. Verified via xxd. No-op change reverted.

- M7 (cache invalidate race): not load-bearing under serial dispatch.
  Documented for the eventual parallel-dispatcher follow-up.

- M8 (release_duplicate_attempts noise during retry windows): observe
  first; the proposed mitigation (skip audit if verified_at younger
  than 10min) adds complexity that may itself be wrong.

- Mi1, Mi2, N2, N3: cosmetic.

83 aggregator tests pass (was 65). Typecheck clean. Zero lint
diagnostics in apps/aggregator.

* fix(aggregator): round 2 adversarial review fixes

Round-2 review found 8 byproduct bugs introduced by the round-1 fixes
themselves. Per-finding rationale:

HIGH

- #1: refreshPackageLatest TOCTOU race. Two concurrent consumer
  invocations could each SELECT max version_sort, then race their
  UPDATEs, leaving packages.latest_version regressed (final write
  wins from the older snapshot). Replaced the SELECT-then-UPDATE
  pair with a single UPDATE using correlated subqueries; D1
  serialises the read+write at write-commit time, so concurrent
  callers always compute against the actual current state.
  Capabilities now extracted via SQLite's json1 functions
  (json_each + json_group_array on $.declaredAccess).

- #2: stale latest_version on refresh failure. INSERT committed,
  refresh threw, dispatcher acked → permanent inconsistency
  because subsequent same-content retries hit DO NOTHING and the
  prior conditional-only refresh skipped. Now insert + refresh run
  in db.batch() — D1 wraps in one transaction, so either both
  commit or both roll back. Same fix in applyDelete (tombstone +
  refresh batched). Refresh runs unconditionally on every release
  ingest path (idempotent; race-safe via #1).

MEDIUM

- #3: mapPdsReason throw escaped the catch. Function-arg evaluation
  ran mapPdsReason(err.reason) BEFORE writeDeadLetter, so a throw
  there crashed the whole batch. Now wrapped in its own try/catch
  with an UNEXPECTED_ERROR fallback so the dead_letters write still
  happens.

- #4: isCommitEvent predicate trusted `kind` only. A producer
  emitting `{kind: "commit"}` without a structurally valid `commit`
  field would slip through and crash the ingestor at
  `event.commit.collection`; cursor wouldn't advance, Jetstream
  would replay the malformed event forever. Predicate now verifies
  commit.collection / commit.rkey / commit.operation are present
  strings. Test stub updated to match what real producers emit.

- #5: parseReleaseRkey URIError on malformed %-encoding. A delete
  with rkey "demo:1.0.0%XX" threw URIError → not caught as
  IngestError → controller.retry() → 5 wasted attempts before DLQ.
  Now caught and returned as null so applyDelete silently no-ops.

- #6: DLQ had no consumer. Configured a second consumer in
  wrangler.jsonc draining `emdash-aggregator-records-dlq`. New
  drainDeadLetterBatch handler logs each job to Workers logs +
  writes a `dead_letters` forensics row, then acks. Until
  reconciliation lands, this prevents permanent silent drops of
  legitimate-but-out-of-order release events that exhausted retries.

- #7: release_duplicate_attempts unbounded under spam. Hostile
  publisher pumping the same different-content payload could fill
  the audit table indefinitely. Added UNIQUE(did, package, version,
  attempted_record_blob) constraint + ON CONFLICT DO NOTHING on the
  insert, so true duplicates dedupe at the storage layer.

LOW

- #8: previously-claimed "MissingDependencyError retry" test
  actually only exercised the PDS_HTTP_ERROR(5xx) path. Added a
  proper test using the new ConsumerDeps.verify injection point —
  exercises the writer's parent-profile pre-check and asserts the
  dispatcher routes MissingDependencyError → controller.retry().

WIRING / TESTABILITY

- ConsumerDeps gained an optional `verify` override, defaulting to
  fetchAndVerifyRecord. Tests can inject a stub that returns a
  synthetic VerifiedPdsRecord without standing up a real CAR
  fixture. This is what makes the MissingDependencyError test
  reachable inside the workers pool.

- index.ts queue() handler now dispatches by batch.queue name to
  either processBatch (records) or drainDeadLetterBatch (DLQ).

LINT CLEANUP

- jetstream-client.ts: defined a wider `MaybeCommitEvent` parameter
  type for the predicate so commit-field inspection doesn't need an
  unsafe cast. The type's `commit?` is structurally-typed so any
  RawJetstreamSubscription<E> with E extends {kind: string}
  remains assignable.

- records-consumer.ts: removed unused refreshPackageLatest wrapper;
  callers use refreshPackageLatestStmt directly inside batches.

89 tests pass (was 83). Typecheck clean. Zero lint diagnostics in
apps/aggregator.

Reviewer's verdicts on round-1 fixes I claimed: all present and
structurally correct. The new bugs were byproducts, not regressions.

* fix(aggregator): round 3 adversarial review fixes

Round-3 review found 5 bugs in the round-2 fixes themselves. Per-finding
rationale:

MEDIUM

- #1: drainDeadLetterBatch silently dropped messages on D1 failure.
  The try/catch around writeDeadLetter swallowed errors, then the
  unconditional message.ack() outside the try acked anyway —
  forensics lost AND message gone. The configured max_retries: 3 in
  wrangler.jsonc was dead config because the handler never threw.
  Fix: move ack() inside the try; on error, controller.retry() so
  workerd redelivers per the DLQ consumer's max_retries.

- #2: FTS thrashing on idempotent refresh. Round-2 traded
  releaseSetChanged guard for "always run refresh" to fix the
  insert-success / refresh-failure consistency bug. But the
  unconditional refresh hit the packages_au AFTER UPDATE trigger,
  which DELETEs and re-INSERTs into packages_fts on every row touch
  — even when latest_version + capabilities are unchanged. Every
  same-content Jetstream replay (the common case) reindexed FTS for
  no reason. Fix: extend REFRESH_PACKAGE_LATEST_SQL's WHERE clause
  to short-circuit at SQL level when both target columns already
  hold the computed values. Avoids the trigger fire entirely; keeps
  the round-2 atomicity (insert + refresh still in one batch).

MINOR

- #3: applyDelete malformed rkey was a silent no-op. Round-2 fix
  correctly stopped the URIError-causes-retry path but overcorrected
  by removing the audit trail. Operators investigating "why didn't
  this delete take effect?" had nothing to look at. Now throws
  IngestError("RKEY_MISMATCH") so the dispatcher writes a
  dead_letters row before acking.

- #4: release_duplicate_attempts.rejected_at was frozen at first
  attempt. Hostile publisher pumping the same bytes for a year showed
  in the audit table as a single row dated a year ago. Conflict
  clause now DO UPDATE SET rejected_at = excluded.rejected_at so the
  audit row tracks the latest attempt; same-bytes deduping at the
  storage layer still works.

- #5: idx_release_duplicates was redundant with the new UNIQUE
  constraint's implicit index (the UNIQUE on (did, package, version,
  attempted_record_blob) covers all (did, package, version) prefix
  lookups). Dropped the explicit index — fewer indexes to maintain
  on each write.

ASKED-ABOUT, NO BUG FOUND

Reviewer verified all 12 prompt concerns either lead to fixes above
or are clean: D1 batch atomicity, correlated-subquery semantics under
SQLite snapshot isolation, json_each(NULL) behavior, MaybeCommitEvent
parameter assignability, ConsumerDeps.verify injection correctness,
duplicate dead_letters writes, jetstream-client test stub fidelity,
concurrent dead_letters writes. No round-1 or round-2 finding
regressed.

92 tests pass (was 89). Typecheck clean. Zero lint diagnostics in
apps/aggregator.

The slice has now had three rounds of adversarial review with all
findings addressed in-tree. Outstanding deferred items (M7 cache
race under hypothetical parallel dispatcher, M8 audit-noise
mitigation, B4 production wiring still untested by integration
test) tracked for follow-up PRs.

* fix(aggregator): Copilot review feedback

Seven Copilot comments on PR #975. One real bug + four doc/comment
fixes + one test cleanup + one cosmetic.

REAL BUG

- json_group_array(key) over json_each enumerates in unspecified
  order, so the capabilities JSON string could vary between runs even
  when the key set is unchanged — defeating the WHERE-AND-IS-NOT
  short-circuit and re-firing the packages_au trigger on every
  idempotent refresh. Wrapped both subqueries in
  `(SELECT key FROM json_each(...) ORDER BY key)` so the resulting
  array is order-stable.

DOC FIXES

- pds-verify.ts 404 comment claimed "ack without forensics", but the
  consumer writes a dead_letters row for RECORD_NOT_FOUND (and tests
  assert that behavior). Updated comment to match the implemented
  policy: forensics for both the legitimate-race case and the
  programming-error case, distinguished by reason code for queryability.

- parseReleaseRkey docstring claimed "callers should treat null as
  no-op", but applyDelete now throws IngestError on null to surface
  the malformed delete in dead_letters. Updated docstring to describe
  the actual contract.

- dead_letters table comment listed reason values that don't match
  the implemented `DeadLetterReason` union. Replaced with the actual
  list and noted the union lives in records-consumer.ts. Also
  clarified payload is UTF-8 JSON bytes, not raw record bytes.

- wrangler.jsonc DLQ-consumer comment claimed "repeated failures get
  acked after retries". Actual behavior: handler calls retry() on D1
  failure, max_retries: 3 then workerd drops (no DLQ-of-DLQ).

TEST CLEANUP

- Removed an empty placeholder test that documented why the dispatcher's
  retry-on-MissingDependency wasn't covered. The proper coverage now
  exists in the dispatcher suite via ConsumerDeps.verify injection;
  the placeholder was dead.

- Stripped review-finding shorthand codes (Mi6, B3, round-3 #1, etc.)
  from describe-block names. The codes were leaking review-process
  scaffolding into permanent test descriptions.

91 tests pass (was 92 — dropped the empty placeholder). Typecheck
clean. Zero lint diagnostics in apps/aggregator.

* fix(aggregator): second round of Copilot review feedback

Four more Copilot comments. Two real bugs + two doc fixes.

REAL BUGS

- DidResolver.invalidate() bumped known_publishers.last_seen_at
  backwards to 1970-01-01. The implementation called cache.upsert()
  with `new Date(0)`, and the D1 binding writes the same timestamp
  to all three of `pds_resolved_at`, `first_seen_at`, and
  `last_seen_at`. Net effect: invalidating a publisher's cached
  signing key (after a key rotation) corrupted the
  membership/observation timestamps as a side-effect.

  Fix: added a dedicated `expire(did)` method to the DidDocCache
  interface. The D1 binding's expire only touches
  `pds_resolved_at` (sets to epoch); the Map-backed test cache does
  the same in-memory. Resolver's `invalidate()` delegates to
  `cache.expire()` instead of forcing the issue through `upsert()`.

- isCommitEvent didn't validate `commit.cid`. The ingestor reads
  `event.commit.cid` for non-delete operations, so a malformed
  commit event with no cid would slip through and produce a
  RecordsJob with `cid: undefined` — which the consumer would then
  try to verify against, with no useful error path.

  Fix: extended the predicate to require `cid` to be a string when
  `operation !== "delete"`. Delete events legitimately have no cid
  so the check is conditional. Test stub updated to match.

DOC FIXES

- applyDelete comment for package.profile claimed "we don't cascade
  because doing so silently throws away publication history". The
  schema FK has been ON DELETE CASCADE since the round-1 fixes (so
  out-of-order Jetstream delivery doesn't fail with FK violation
  when a profile-delete arrives before its release-deletes). Updated
  the comment to describe the actual cascade behavior + the audit
  history that DOES survive (release_duplicate_attempts,
  dead_letters).

- release_duplicate_attempts schema comment said the consumer used
  `ON CONFLICT … DO NOTHING`, but the round-3 fix changed it to
  `DO UPDATE SET rejected_at = excluded.rejected_at` so operators
  can read freshness from the audit row. Updated the comment.

95 tests pass (was 91; added 2 jetstream-client cid-validation
tests + 2 did-resolver expire tests). Typecheck clean. Zero lint
diagnostics in apps/aggregator.

* fix(aggregator): third round of review feedback

ask-bonk + Copilot caught 5 real bugs and 1 stale comment.

REAL BUGS

- Duplicate-version detection compared raw CAR bytes. CARs include
  the publisher's commit + MST proof, which churns whenever the
  publisher writes any other record in the same repo — so a benign
  re-fetch of an unchanged record produced different bytes and got
  misclassified as an immutability violation.

  Fix: compare the verified record CID instead. CIDs are
  content-addressed and stable for unchanged records. Schema
  updated: `release_duplicate_attempts` gained `attempted_cid TEXT
  NOT NULL` and the UNIQUE constraint now uses it instead of
  `attempted_record_blob`. The blob is still kept for forensics so
  operators can inspect what was actually attempted; the conflict
  clause refreshes both `rejected_at` and `attempted_record_blob`
  so the latest envelope wins. Comparison logic in the writer reads
  the existing CID out of `signature_metadata` JSON via a small
  `parseCid` helper.

- `processBatch` for-loop didn't isolate per-message failures. A
  `writeDeadLetter` throw inside `processMessage` (e.g. transient D1
  hiccup mid-batch) escaped to the loop and halted it, leaving
  subsequent messages without ack/retry. With max_batch_size 25,
  one D1 hiccup could waste up to 24 PDS verification round-trips
  on redelivery. Now each message is wrapped in try/catch with a
  retry() on uncaught throw, matching the shape `drainDeadLetterBatch`
  already uses.

- `computeVersionSort`'s `.zzz` final-release sentinel didn't
  actually beat all valid prereleases — `1.0.0-zzzz` sorts AFTER
  `1.0.0` because `"zzzz"` is lexically greater than `"zzz"`. Switched
  the sentinel to `~` (ASCII 126), one above the prerelease
  alphabet's max char (`z` at 122). Final releases now sort after
  any prerelease at the same major.minor.patch.

- `parseReleaseRkey` validated nothing about its components — a
  malformed rkey like `demo:1.0.0:extra` parsed as
  `pkg=demo`, `version=1.0.0:extra`, then UPDATE matched no row and
  silently acked. Now validates pkg with PACKAGE_SLUG_RE and version
  with SEMVER_RE; returns null on mismatch so applyDelete throws
  IngestError → forensics row.

- `isCommitEvent` accepted any string for `commit.operation`. An
  unknown operation slipping through would produce a RecordsJob the
  consumer can't dispatch on — landing as UNEXPECTED_ERROR in
  dead_letters. Now restricts to {create, update, delete}.

DOC FIX

- pds-verify.test.ts header claimed end-to-end coverage of the
  `verifyRecord` handoff exists in records-consumer.test.ts via
  MockPds + FakePublisher. Actually it's stubbed via
  ConsumerDeps.verify — the fixture can't load in the workers test
  pool. Updated comment to explain the actual coverage shape.

102 tests pass (was 95). Typecheck clean. Zero lint diagnostics.
ascorbic added a commit that referenced this pull request May 13, 2026
Addresses 7 findings from the round-6 adversarial review and
documents the eighth.

#1 (high) Capability consent bypass [registry.ts, RegistryPluginDetail.tsx]
The drift check was gated on the client sending acknowledgedDeclaredAccess.
If the publisher's release record had no extension, the admin saw an
empty permission dialog, omitted the acknowledgement, and the server
skipped the check entirely -- letting a bundle whose manifest declares
real capabilities slip through behind an empty consent UI. Server now
extracts capabilities from the bundle manifest after download and
refuses with DECLARED_ACCESS_REQUIRED if the bundle declares any
capabilities and no acknowledgement was sent. Client always sends the
list (empty when no extension) so the new server check is always armed.

#2 (high) Concurrent install bundle deletion [registry.ts]
Two parallel installs of the same (did, slug, version) both passed the
pre-existing-row check, both uploaded to the same deterministic R2
prefix, and one then won the state-row PK race. The loser's catch block
deleted the R2 bundle the winner had just written. On state-write
failure we now re-query the state row: if a winner exists, we lost the
race and must not touch the R2 bundle. Cleanup runs only when the
failure is a real DB error, not a lost concurrent install.

#3 (high) SSRF via DNS-resolving public hostnames [registry.ts, ssrf.ts moved]
Literal-IP blocklist alone left a DNS-rebinding gap: any public DNS
service resolving an attacker-chosen hostname to loopback / RFC1918 /
169.254.169.254 passed the URL check. The import pipeline already
shipped resolveAndValidateExternalUrl which does Cloudflare DoH
resolution and rejects on any forbidden resolved address; reuse it
for artifact downloads. Move src/import/ssrf.ts to src/security/ssrf.ts
to reflect that it's not import-specific. Leave a re-export shim at
the old path so 13 existing callers keep working unchanged. Add
#security/* path alias.

#5 (high) Aggregator-supplied handles treated as verified [PublisherHandle.tsx]
usePublisherHandle returned status: 'ok' with the aggregator-supplied
handle whenever one was present, skipping local DID->handle round-trip.
A compromised aggregator could label an attacker DID as e.g.
'stripe.com' and the UI would render it as verified. Always run
LocalActorResolver via resolveDidToHandle; use the aggregator handle
only for a cross-check. If the aggregator's claim differs from the
verified handle, mark the publisher invalid.

#6 (medium) Postgres migration 038 schema-qualification [038_registry_plugin_state.ts]
The columns probe queried information_schema.columns without filtering
by table_schema. A _plugin_state table in another schema (multi-tenant
Postgres, per-test schemas) could make the migration skip the column
adds. Filter by table_schema = current_schema().

#7 (medium) Install errors leak full artifact URLs [registry.ts]
fetchArtifact recorded each full URL in the joined error message that
bubbled up to the admin client. Artifacts hosted on storage backends
often carry presigned tokens in the query string; failed installs were
leaking those into HTTP responses and logs. Strip query and fragment
when building client-visible errors (origin + path only); log the full
URL server-side for debugging.

#8 (medium) Credentialed aggregator URLs accepted [config.ts]
validateAggregatorUrl accepted https://user:[email protected].
The normalized URL ends up in the admin manifest and is shipped to
every admin browser; browser fetch() also rejects credentialed URLs
outright. Reject them at config-validation time.

#4 (high, documented not fixed) Aggregator-trust-root scope [types.ts]
Full MST proof / publisher signature verification is not in this PR;
the server still trusts the aggregator-supplied (did, slug, checksum,
artifact URL). Expand the JSDoc on EmDashConfig.experimental.registry
to spell out exactly what the v1 trust contract is, what EmDash does
verify independently (checksum, manifest id/version/capabilities), and
what it doesn't (release-record signatures, replay). Recommendation:
point aggregatorUrl only at an aggregator you operate or trust at
centralized-source level until signature verification lands.
ascorbic added a commit that referenced this pull request May 14, 2026
…#1011)

* fix(deps): catalog-pin zod so trusted plugins typecheck

Astro bundles its own Zod and re-exports it as 'astro/zod'. Trusted
plugins like @emdash-cms/plugin-forms import their route schemas via
'astro/zod', then pass those schemas to definePlugin() in core. With
emdash's 'zod: ^4.3.5' resolving independently of Astro's caret,
pnpm kept two Zod 4 patches in the tree (e.g. 4.3.6 alongside 4.4.1).

Zod 4 embeds its semver in the type system, so two patches of Zod 4
are not assignable to each other. The forms plugin's route schemas
(ZodObject<..., $strip>) were rejected by PluginRoute<TInput>['input']
(ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>) with
'Type "3" is not assignable to type "4"' on the internal version
field. The native definePlugin overload silently failed, TS fell
through to the StandardPluginDefinition overload, and reported a
misleading 'id does not exist' error -- masking 8 cascading errors.

Catalog-pinning Zod forces a single workspace-wide instance and
restores normal overload resolution. No code changes needed in core
or plugins/forms.

Also adds a pnpm-workspace.yaml comment explaining the gotcha so the
next person doesn't bump emdash's pin past Astro's range.

* feat(registry): experimental decentralized plugin registry

Adds opt-in support for installing sandboxed plugins from the
decentralized plugin registry described in RFC #694. Enabled via
`experimental.registry.aggregatorUrl` in the EmDash integration
options; when set, the admin UI replaces marketplace browse/install
with the registry path.

Server: new install handler (RFC verification chain), endpoint at
POST /_emdash/api/admin/plugins/registry/install, migration 038 adds
`source = 'registry'` plus `registry_publisher_did` /
`registry_slug` columns on `_plugin_state`, runtime sync split into
shared marketplace + registry tiers via a normalized opaque
`r_<hash>` plugin id.

Browser: aggregator XRPC calls go direct from the admin UI via
@emdash-cms/registry-client. Install POST runs through the server.
Includes a minimum-release-age policy with a per-publisher exclude
allowlist, enforced both client-side (UX) and server-side (gate).

Hardening (5 rounds of adversarial review): bundle id rewritten to
the derived pluginId before storage, aggregator identity
cross-checked, artifact and aggregator URLs validated for SSRF
(https-only in prod, IPv6 brackets handled), per-request and total
budgets on every outbound call, decompressed bundle capped at 256
KiB to match the RFC publish-time limit, migration 038 idempotent
on both SQLite and Postgres.

Known gaps tracked for follow-up: full MST signature verification
against the publisher's PDS, multibase multihash decoding (hex SHA-256
is accepted today), registry plugin update + uninstall handlers.

* fix(registry-lexicons): drop codegen from build script

The generated lexicon types are committed to git so consumers don't
need the codegen toolchain. Running lex-cli generate as part of the
default build pipeline broke Cloudflare Pages builds for sites that
pull registry-lexicons in transitively, because lex-cli imports
lex.config.ts directly and Node in the CF Pages build environment
can't load .ts natively.

Codegen moves to a separate `regen` script (`pnpm regen` runs
codegen + full build). Maintainers run it when they edit the
lexicons; consumers just consume the committed output.

* fix(registry): copilot review fixes

- Drift check normalizes capabilities (filter strings, dedupe, sort) on
  both browser and server so reorderings or junk entries can't trigger
  spurious rejection. Adds a shared normalizeCapabilities helper in
  registry/config.ts and a mirror in admin/lib/api/registry.ts.
- RegistryPluginDetail no longer trusts the aggregator-supplied
  ext?.capabilities as already-validated string[]; runs it through
  normalizeCapabilities before display and before send.
- Fix stale '32 MiB' docstring on extractBundle (cap is actually
  MAX_DECOMPRESSED_BUNDLE_BYTES = 256 KiB).
- Fix plugin-id.ts JSDoc: validatePluginIdentifier regex is
  /^[a-z][a-z0-9_-]*$/ (allows hyphens); the prior 'cannot collide
  with marketplace ids' claim was too strong and is now framed as
  'syntactically distinct, plus an explicit pre-existing-row check
  in the install handler.'

* fix(registry): address review findings + CI failures

CI fixes:
- Rename normalizeCapabilities -> canonicalCapabilitiesForDriftCheck
  to avoid namespace clash with the existing capability normalizer
  exported from @emdash-cms/plugin-types via core's index. The old
  name shadowed plugin-types' helper at the top level of core's dist,
  which made the definePlugin() overload set look ambiguous to TS in
  plugins/forms and caused a typecheck cascade there.
- [...seen].toSorted() instead of [...seen].sort() to clear the
  e18e/prefer-spread-syntax + unicorn/no-array-sort lint errors.

Review findings (ask-bonk[bot]):
- HIGH: drift check tripped on every install when the release record's
  extension was empty. The browser now omits acknowledgedDeclaredAccess
  when capabilities is empty, opting out of the server-side drift gate
  for the (currently common) case where publishers haven't filled in
  the extension block. The bundle's real capabilities are still bound
  to the checksum-verified bytes.
- HIGH: DID-only publishers (no resolvable handle) could be linked from
  the browse grid but never installed because the server rejects
  handles without a '.'. Cards now render as non-interactive with a
  'Publisher handle unresolved' badge; the detail page surfaces a
  matching warning and disables Install.
- MEDIUM: registry-enabled sites were unconditionally routing existing
  marketplace plugin detail URLs to RegistryPluginDetail, breaking deep
  links. Detail-route selection now discriminates by param shape
  (pluginId.includes('/')) rather than the manifest flag.
- MEDIUM: state-row write failure after storeBundleInR2 left orphan
  bundles. Best-effort cleanup in the catch via deleteBundleFromR2.
- LOW: parseDurationSeconds runs on the user-supplied integration
  option per install (not the already-normalized manifest shape). Wrap
  in try/catch and surface as REGISTRY_POLICY_INVALID rather than
  letting it bubble to a generic INSTALL_FAILED.
- LOW: validator-pattern doc drift in plugin-id.ts (already fixed in
  the prior commit).

* fix(registry): move registry config types to their own module

The new RegistryConfig + ExperimentalConfig interfaces lived alongside
definePlugin's overloads in astro/integration/runtime.ts. tsdown +
rolldown's chunking decided to inline a bigger subset of plugin-related
types into the entry chunk as a result, which broke definePlugin()
overload resolution for trusted plugins building against core's dist
on CI (plugins/forms failed with 'id does not exist in type
StandardPluginDefinition').

Move both types to packages/core/src/registry/types.ts (still re-exported
from runtime.ts for backwards compatibility) so the chunking matches
main's layout and definePlugin's overloads resolve as before.

* fix(registry): wire up real-world install + display polish

Aggregator (apps/aggregator):
- Add CORS to /xrpc/* so the admin UI can call it from any origin
  (preflight 204, response headers on every method). Aggregator is a
  public read-only service; * is correct here.

Core (packages/core):
- Implement multibase-multihash checksum verification by re-encoding
  our SHA-256 digest in the same 'b<base32>' shape the registry CLI
  produces, rather than decoding the publisher's checksum. Same trust
  contract, no base32 decoder needed. Bare hex SHA-256 still accepted
  as a convenience fallback.
- Switch install handler to take 'did' (not handle) so packages whose
  handle the aggregator couldn't resolve are still installable. The
  browser resolves handle→DID via the aggregator before posting and
  sends DID directly; the server skips resolvePackage and goes
  straight to getPackage.
- Coerce 'experimental.registry' bare-string shorthand into the full
  RegistryConfig object via 'coerceRegistryConfig'. 'registry:
  "..."' is now equivalent to 'registry: { aggregatorUrl: "..." }'.
- Plumb 'experimental' through the integration's serializableConfig
  so the manifest endpoint actually sees the user's registry block.
  Previously it was being stripped, so the admin UI never branched to
  the registry path.
- Split RegistryConfig + ExperimentalConfig types into their own
  module (registry/types.ts) so they don't get bundled into the
  astro/integration/runtime.ts dist chunk -- the wider inlining was
  breaking definePlugin overload resolution for trusted plugins
  building against core's dist.

Admin (packages/admin):
- New <PublisherHandle> component + usePublisherHandle hook with
  tri-state result ('ok' / 'invalid' / 'missing'). Renders @handle,
  'Unverified publisher' (red), or DID respectively. Uses
  @atcute/identity-resolver's LocalActorResolver for bidirectional
  handle verification, localStorage-cached for 24h.
- Detail page disables install on 'invalid' status (publisher claims
  a handle that doesn't round-trip back to its DID -- impersonation
  risk). Surfaces 'We couldn't verify this publisher's identity'
  alert in plain language.
- Detail page reads installed state from fetchPlugins() and swaps
  the Install button to 'Installed' (disabled) when the package
  already has a 'source = "registry"' row matching its DID + slug.
  React Query's existing ['plugins'] invalidation handles the
  post-install UI update.
- Browse cards reuse <PublisherHandle> (variant='card') and link by
  handle when available, DID otherwise. Detail page parses either
  form from the URL.
- Browser sends 'did' (not handle) in the install POST.

Workspace:
- '@cloudflare/kumo' moved to the pnpm catalog and bumped to ^1.16.0
  workspace-wide. Older 1.10.0 was missing Sidebar export and being
  hoisted into the admin via packages/blocks's transitive dep.
- Add '@atcute/multibase' to core (for checksum encoding) and
  '@atcute/identity-resolver' to admin (for DID->handle resolution).
- Update DEFAULT_AGGREGATOR_URL + DiscoveryClient doc example from
  'experimental-registry.emdashcms.com' to 'registry.emdashcms.com'
  (the actual production host).

* fix(registry): adversarial review round 6 findings

Addresses 7 findings from the round-6 adversarial review and
documents the eighth.

#1 (high) Capability consent bypass [registry.ts, RegistryPluginDetail.tsx]
The drift check was gated on the client sending acknowledgedDeclaredAccess.
If the publisher's release record had no extension, the admin saw an
empty permission dialog, omitted the acknowledgement, and the server
skipped the check entirely -- letting a bundle whose manifest declares
real capabilities slip through behind an empty consent UI. Server now
extracts capabilities from the bundle manifest after download and
refuses with DECLARED_ACCESS_REQUIRED if the bundle declares any
capabilities and no acknowledgement was sent. Client always sends the
list (empty when no extension) so the new server check is always armed.

#2 (high) Concurrent install bundle deletion [registry.ts]
Two parallel installs of the same (did, slug, version) both passed the
pre-existing-row check, both uploaded to the same deterministic R2
prefix, and one then won the state-row PK race. The loser's catch block
deleted the R2 bundle the winner had just written. On state-write
failure we now re-query the state row: if a winner exists, we lost the
race and must not touch the R2 bundle. Cleanup runs only when the
failure is a real DB error, not a lost concurrent install.

#3 (high) SSRF via DNS-resolving public hostnames [registry.ts, ssrf.ts moved]
Literal-IP blocklist alone left a DNS-rebinding gap: any public DNS
service resolving an attacker-chosen hostname to loopback / RFC1918 /
169.254.169.254 passed the URL check. The import pipeline already
shipped resolveAndValidateExternalUrl which does Cloudflare DoH
resolution and rejects on any forbidden resolved address; reuse it
for artifact downloads. Move src/import/ssrf.ts to src/security/ssrf.ts
to reflect that it's not import-specific. Leave a re-export shim at
the old path so 13 existing callers keep working unchanged. Add
#security/* path alias.

#5 (high) Aggregator-supplied handles treated as verified [PublisherHandle.tsx]
usePublisherHandle returned status: 'ok' with the aggregator-supplied
handle whenever one was present, skipping local DID->handle round-trip.
A compromised aggregator could label an attacker DID as e.g.
'stripe.com' and the UI would render it as verified. Always run
LocalActorResolver via resolveDidToHandle; use the aggregator handle
only for a cross-check. If the aggregator's claim differs from the
verified handle, mark the publisher invalid.

#6 (medium) Postgres migration 038 schema-qualification [038_registry_plugin_state.ts]
The columns probe queried information_schema.columns without filtering
by table_schema. A _plugin_state table in another schema (multi-tenant
Postgres, per-test schemas) could make the migration skip the column
adds. Filter by table_schema = current_schema().

#7 (medium) Install errors leak full artifact URLs [registry.ts]
fetchArtifact recorded each full URL in the joined error message that
bubbled up to the admin client. Artifacts hosted on storage backends
often carry presigned tokens in the query string; failed installs were
leaking those into HTTP responses and logs. Strip query and fragment
when building client-visible errors (origin + path only); log the full
URL server-side for debugging.

#8 (medium) Credentialed aggregator URLs accepted [config.ts]
validateAggregatorUrl accepted https://user:[email protected].
The normalized URL ends up in the admin manifest and is shipped to
every admin browser; browser fetch() also rejects credentialed URLs
outright. Reject them at config-validation time.

#4 (high, documented not fixed) Aggregator-trust-root scope [types.ts]
Full MST proof / publisher signature verification is not in this PR;
the server still trusts the aggregator-supplied (did, slug, checksum,
artifact URL). Expand the JSDoc on EmDashConfig.experimental.registry
to spell out exactly what the v1 trust contract is, what EmDash does
verify independently (checksum, manifest id/version/capabilities), and
what it doesn't (release-record signatures, replay). Recommendation:
point aggregatorUrl only at an aggregator you operate or trust at
centralized-source level until signature verification lands.

* fix(registry): adversarial review round 7 followups

Two LOW findings from the round-7 review (PR #1011 comment).

NSID exact-match in RegistryPluginDetail.tsx
  Round-6 left a startsWith() match on the release-extension key.
  RFC 0001 fixes the NSID for the release extension; accepting prefix
  variants (...releaseExtensionV2, ...releaseExtension.deprecated)
  would let a publisher render a different capability list than the
  canonical key would. Use exact-equality keyed lookup.

Registry plugin uninstall affordance in PluginManager.tsx
  Registry-installed plugins appear in PluginManager but the Uninstall
  button is gated on isMarketplace. Admins see a permanent-looking
  install with no way to remove it short of editing the DB and R2 by
  hand. Add an inline note for source === 'registry' rows that says
  uninstall isn't available yet and points the admin at the disable
  toggle. Full uninstall handler lands in a follow-up PR.
signal-alchemist pushed a commit to signal-alchemist/emdash that referenced this pull request Aug 25, 2026
@ask-bonk ask-bonk Bot mentioned this pull request Sep 19, 2026
2 of 19 tasks
@emdashbot emdashbot Bot added review/needs-review No maintainer or bot review yet and removed review/needs-review No maintainer or bot review yet labels Oct 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

review/needs-review No maintainer or bot review yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant