Skip to content

feat(brand-registry): self-service domain claim challenge (#3176) - #3189

Merged
bokelley merged 4 commits into
mainfrom
bokelley/brand-claim-challenge
Apr 25, 2026
Merged

bokelley merged 4 commits into
mainfrom
bokelley/brand-claim-challenge

Conversation

@bokelley

@bokelley bokelley commented Apr 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Self-service brand-claim challenge for the verified-domain takeover path, built on the WorkOS Domain Verification API (rebuilt — see "Why the rebuild" below). Closes the policy half of #3176.

Why the rebuild

The first cut of this PR rolled its own file-placement challenge with custom token+expiry schema. WorkOS already ships exactly this primitive (DNS TXT, webhook-driven, registrar-level proof) via workos.organizationDomains, with zero callers in the tree. Reviewer caught the duplication. Rebuilding on WorkOS gives us:

  • Stronger evidence: DNS TXT proves registrar-level control vs file-placement which only proves web-server control
  • "One verified domain per org" enforcement at the WorkOS layer — verified-vs-verified collisions are unreachable
  • Webhook-driven state with no polling
  • No new schema — WorkOS holds the verification state; we just listen for webhooks

Flow

POST /api/me/member-profile/brand-claim/issue   { "domain": "kyber1.com" }
  → workos.organizationDomains.create(orgId, domain)
  → { workos_domain_id, verification_token, verification_prefix, instructions: "publish DNS TXT" }

(member publishes  _workos.kyber1.com TXT  with  workos_token_value )

POST /api/me/member-profile/brand-claim/verify  { "domain": "kyber1.com", "adopt_prior_manifest": false }
  → workos.organizationDomains.verify(domainId)
  → on success: applyVerifiedBrandClaim mirrors state into brands row
  → { verified: true, transferred: true, adopted_prior_manifest: false, brand: {...} }

Branching

  • Domain unowned anywhere → WorkOS create succeeds, member publishes TXT, verify mirrors state into brand registry
  • Domain attached to caller's org but pending → re-issue is idempotent (returns existing pending state)
  • Domain attached to caller's org and verified → idempotent: mirrors registry, returns success
  • Domain attached to ANOTHER org (verified) → WorkOS rejects create with 422; we surface as 409 with escalation hint, member routes through the existing dispute path
  • Orphaned brand registry row → on verify success, adopt_prior_manifest: true keeps the prior brand identity (acquisitions); default starts fresh

Cross-org dispute response now mentions this path

The 409 from PUT /brand-identity (added in #3168) now reads "If you actually control {domain}, you can prove it via the domain verification challenge — call POST /api/me/member-profile/brand-claim/issue and follow the instructions." Closes the "self-service hint deferred" gap.

Webhook handler also syncs the registry

organization_domain.verified webhook now also calls applyVerifiedBrandClaim so admins flipping state via the WorkOS dashboard get the brand registry sync for free. Idempotent with the inline write in /verify — whichever lands first wins.

Test plan

  • 5 integration tests covering registry-side idempotency: create from nothing, no-op replay, transfer from unverified incumbent, default fresh manifest, opt-in adopt branch
  • 834 unit tests still pass
  • Type-check clean
  • Reviewer to verify on staging end-to-end against a real WorkOS org

Out of scope

  • Member chat tool wrapping issue+verify (easy follow-up)
  • UI surface for the DNS TXT instructions (the API now returns enough info; just needs a frontend component)

🤖 Generated with Claude Code

bokelley and others added 3 commits April 25, 2026 13:25
Members who control a domain can now prove it via a file-placement
challenge instead of dead-ending on the cross-org escalation path:

* POST /api/me/member-profile/brand-claim/issue — generates an
  adcp-claim-{uuid} token, stamps it on the brand row with the
  caller's org id and a 7-day TTL, and returns the placement URL
  (https://{domain}/.well-known/adcp-claim/{token}).
* POST /api/me/member-profile/brand-claim/verify — fetches the
  placement URL via safeFetch (SSRF-protected), confirms the body
  matches the issued token, and atomically applies the claim:
  - Unowned brand → claim ownership, mark domain_verified.
  - Owned but not verified → transfer ownership.
  - Orphaned brand → claim, clear orphan flag, default to fresh
    manifest (or adopt_prior_manifest: true to keep prior identity).
  - Verified incumbent of a different org → REFUSE to auto-resolve;
    file a sensitive_topic escalation. Verified-vs-verified is a
    governance call.

The token is bound to the org that issued it, so a stale token left
by a previous claimant can't be used by a later one. Subsequent
issues for the same domain overwrite — at most one outstanding
challenge per domain. Expired tokens return 410.

The cross-org dispute response in PUT /brand-identity now mentions
this path so a member hitting the 409 sees the self-service route.

Migration 431 adds verification_token_org_id +
verification_token_expires_at columns. The existing
verification_token column was a stub from before #3137; this PR is
its first real caller.

Includes 6 integration tests covering issue/verify/expire,
overwrite-on-reissue, claim of unowned brand, orphan adoption (both
adopt and start-fresh branches), and atomic token clearing.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The first cut of #3189 rolled its own file-placement challenge with a
custom token+expiry schema and polling /verify endpoint. WorkOS already
ships exactly this primitive (DNS TXT, webhook-driven, registrar-level
proof) via workos.organizationDomains, with zero callers in our tree.
Reviewer caught the duplication. Reworking on WorkOS gives us:

* Stronger evidence (DNS TXT vs file placement)
* "One verified domain per org" enforcement at the WorkOS layer —
  verified-vs-verified collisions are unreachable
* Webhook-driven state with no polling
* No new schema

Changes:

* /brand-claim/issue calls workos.organizationDomains.create and returns
  the WorkOS-issued verification_token + verification_prefix so the
  caller knows what DNS TXT record to publish. Idempotent re-issue
  surfaces the existing pending domain instead of erroring.
* /brand-claim/verify calls workos.organizationDomains.verify, then
  mirrors the verified state into the brand registry inline via
  applyVerifiedBrandClaim. Adopt-vs-fresh manifest decision flows
  through adopt_prior_manifest in the request body, same shape the
  PUT /brand-identity contract uses.
* organization_domain.verified webhook handler also calls
  applyVerifiedBrandClaim so admins flipping state via the WorkOS
  dashboard get the brand registry sync for free. Idempotent with the
  inline write — whichever lands first wins.
* applyVerifiedBrandClaim becomes an INSERT...ON CONFLICT primitive
  (qualified column refs to disambiguate brand_manifest in the
  EXCLUDED branch) so the verify route can hit it whether or not a
  brand row exists yet.

Removed:
* server/src/services/brand-claim-challenge.ts (file-placement service)
* server/src/db/migrations/431_brand_claim_challenge.sql (no new
  columns needed; WorkOS holds the verification state)
* The DB methods issueBrandClaimChallenge / getBrandClaimChallenge
  (WorkOS owns the token now)

Tests:
* server/tests/integration/brand-claim-apply-verified.test.ts pins the
  registry-side idempotency contract: creates a verified row from
  nothing, no-op on second call, transfers from unverified incumbent,
  default fresh manifest, opt-in adopt branch.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Code-reviewer flagged a real ship-blocker: the webhook backstop calling
applyVerifiedBrandClaim with default fresh-manifest options would
clobber a manifest the inline /verify route had just adopted. Split
into two methods — applyVerifiedBrandClaim (manifest-aware, used by
/verify) vs markBrandDomainVerified (sync-only, used by webhook).
The webhook path now sets ownership/verified flags but never touches
brand_manifest. Skip-if-already-verified guard prevents needless
updated_at churn on retries.

Security-reviewer flagged two real Mediums:
* /brand-claim/issue + /verify now require admin/owner role on the
  caller's org (matches the create-profile pattern at line 279). Was
  previously reachable by any rank-and-file member.
* New assertClaimableBrandDomain rejects shared-platform domains
  (vercel.app, github.io, co.uk, etc.) before issuing the WorkOS
  challenge. Letting one tenant claim the apex would steal the brand
  identity for every co-hosted site.

Plus several smaller items:
* Top-level import of BrandDatabase in workos-webhooks.ts (was a
  per-event dynamic import).
* WorkOS 422 disambiguation: collision-vs-syntactic via response code
  + message inspection. A typo'd domain no longer gets told to "open
  an escalation" when the real issue is malformed input.
* Inline /verify uses workos.organizationDomains.verify directly (was
  a hand-rolled SDK shape cast).
* Response field renamed transferred → newly_verified — accurate when
  the domain was already verified before this call vs newly transferred.
* Semgrep "error message exposed to client" finding: the
  assertValidBrandDomain catch was leaking err.message; now returns a
  generic message and logs the underlying error.

Test additions:
* webhook-after-adopt scenario (would have caught the blocker).
* webhook claims unowned domain (admin-dashboard path).
* webhook is no-op when row is already verified to same org.

Total integration coverage now 8 cases.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
* Drop unused assertValidBrandDomain import from member-profiles.ts.
  assertClaimableBrandDomain wraps it internally.
* Extract isVerifiedDomainState helper. Replaces two String(state)
  casts and their multi-line comments with one named predicate at
  the top of the file. The SDK-narrowing rationale lives there once.
* Reword webhook handler comment. The dashboard-flip path is the only
  writer for state changes made directly in the WorkOS console; the
  prior comment ("verify route's inline write covers the common case")
  was misleading for that path.
* Drop the skip-update WHERE on markBrandDomainVerified. The
  optimization saved nothing in production load (verified-domain
  webhook retries are rare) and added maintenance fragility — anyone
  adding a column to the SET clause would forget to also add it to the
  WHERE. ON CONFLICT DO UPDATE is now plain idempotent.
* Test simplification: the no-op-when-already-verified case asserted
  on updated_at equality, which depended on the skip-update WHERE.
  Replaced with a direct repeat-call convergence assertion that's
  shape-only and doesn't care about timestamp behavior.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@bokelley
bokelley merged commit dcaf005 into main Apr 25, 2026
13 checks passed
@bokelley
bokelley deleted the bokelley/brand-claim-challenge branch April 25, 2026 21:37
bokelley added a commit that referenced this pull request Apr 25, 2026
- Security M1: callerIsOrgAdmin and resolveBrandClaimOrgOr401 now use
  resolveUserRole so inactive/pending memberships can't pass the gate. A
  removed admin must not be able to claim a brand on the org that
  removed them.
- HTTP response shape: restore { brand } object on /verify success and
  human-readable error strings + domain field across error paths so the
  routes match what shipped in #3189. Add machine-readable code field
  alongside error so chat consumers can branch without prose matching.
- Anti-loop: 60s in-process verify cooldown + explicit STOP guidance in
  chat handler markdown when WorkOS returns still_pending.
- Surface prior_manifest_exists from issue so chat callers can prompt
  the user about the adopt-vs-fresh decision; flow through to verify
  tool description as the precondition for adopt_prior_manifest=true.
- Tighten tool descriptions with explicit "Do NOT use when" clauses to
  stop speculative LLM calls.
- Hoist dynamic imports in member-tools.ts to top of file; brandDb
  becomes a module-scope singleton matching memberDb / orgDb pattern.
- UI: copyDomainClaimField receives the button via inline onclick so it
  no longer depends on event.target inside a microtask. toggleDomainClaim
  tracks open state in JS rather than reading display style.
- Service unit tests (16 cases) covering invalid/shared-platform/eTLD,
  collision disambiguation, idempotent re-issue, prior_manifest_exists
  detection, no_challenge, still_pending, success+brand, and the
  cooldown.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
bokelley added a commit that referenced this pull request Apr 25, 2026
- Security M1: callerIsOrgAdmin and resolveBrandClaimOrgOr401 now use
  resolveUserRole so inactive/pending memberships can't pass the gate. A
  removed admin must not be able to claim a brand on the org that
  removed them.
- HTTP response shape: restore { brand } object on /verify success and
  human-readable error strings + domain field across error paths so the
  routes match what shipped in #3189. Add machine-readable code field
  alongside error so chat consumers can branch without prose matching.
- Anti-loop: 60s in-process verify cooldown + explicit STOP guidance in
  chat handler markdown when WorkOS returns still_pending.
- Surface prior_manifest_exists from issue so chat callers can prompt
  the user about the adopt-vs-fresh decision; flow through to verify
  tool description as the precondition for adopt_prior_manifest=true.
- Tighten tool descriptions with explicit "Do NOT use when" clauses to
  stop speculative LLM calls.
- Hoist dynamic imports in member-tools.ts to top of file; brandDb
  becomes a module-scope singleton matching memberDb / orgDb pattern.
- UI: copyDomainClaimField receives the button via inline onclick so it
  no longer depends on event.target inside a microtask. toggleDomainClaim
  tracks open state in JS rather than reading display style.
- Service unit tests (16 cases) covering invalid/shared-platform/eTLD,
  collision disambiguation, idempotent re-issue, prior_manifest_exists
  detection, no_challenge, still_pending, success+brand, and the
  cooldown.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
bokelley added a commit that referenced this pull request Apr 25, 2026
#3224)

* feat(brand-claim): expose chat tools + member-profile UI for domain challenge

Chat tools `request_brand_domain_challenge` / `verify_brand_domain_challenge`
in the member tool set. Member-profile.html gains a DNS-TXT panel (admin/owner-
only) so members can claim a domain registered to another org without leaving
the app. Pulls the WorkOS orchestration out of the routes into
services/brand-claim.ts so chat handlers and HTTP handlers share one
implementation of the issue/verify flow.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(brand-claim): expert-review fixes for chat tools + UI

- Security M1: callerIsOrgAdmin and resolveBrandClaimOrgOr401 now use
  resolveUserRole so inactive/pending memberships can't pass the gate. A
  removed admin must not be able to claim a brand on the org that
  removed them.
- HTTP response shape: restore { brand } object on /verify success and
  human-readable error strings + domain field across error paths so the
  routes match what shipped in #3189. Add machine-readable code field
  alongside error so chat consumers can branch without prose matching.
- Anti-loop: 60s in-process verify cooldown + explicit STOP guidance in
  chat handler markdown when WorkOS returns still_pending.
- Surface prior_manifest_exists from issue so chat callers can prompt
  the user about the adopt-vs-fresh decision; flow through to verify
  tool description as the precondition for adopt_prior_manifest=true.
- Tighten tool descriptions with explicit "Do NOT use when" clauses to
  stop speculative LLM calls.
- Hoist dynamic imports in member-tools.ts to top of file; brandDb
  becomes a module-scope singleton matching memberDb / orgDb pattern.
- UI: copyDomainClaimField receives the button via inline onclick so it
  no longer depends on event.target inside a microtask. toggleDomainClaim
  tracks open state in JS rather than reading display style.
- Service unit tests (16 cases) covering invalid/shared-platform/eTLD,
  collision disambiguation, idempotent re-issue, prior_manifest_exists
  detection, no_challenge, still_pending, success+brand, and the
  cooldown.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(brand-claim): bound verify cooldown map + drop LLM-leaking message

Caps verifyAttemptTimes at 10K entries with expired-first eviction so a
buggy admin client can't grow the in-process map without limit.

Drops "the LLM should not poll" wording from the still_pending cooldown
message — it ships through the HTTP /verify path too and reads weird to
non-chat consumers. Anti-loop guidance for the LLM still lives in the
chat handler markdown where it belongs.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant