Skip to content

fix(brand-identity): logo registry tooling, validation, and admin queue - #3137

Merged
bokelley merged 3 commits into
mainfrom
bokelley/addie-skills-tools
Apr 25, 2026
Merged

bokelley merged 3 commits into
mainfrom
bokelley/addie-skills-tools

Conversation

@bokelley

Copy link
Copy Markdown
Contributor

Summary

Two member escalations (thehook.es, kyber1.com) hit the same shape of bug: saved logos either didn't render (broken Drive viewer URL stored verbatim in brand_manifest) or were stuck in pending review with no admin path to triage. The capability existed in the database layer but no tool, route, or UI exposed it.

This PR closes the loop end to end:

  • Member self-service — new update_company_logo Addie tool. A logged-in member can now say "fix my logo" and Addie has the capability instead of escalating.
  • Admin moderation — list_pending_brand_logos, list_brand_logos, review_brand_logo for the aao-admin queue. getPendingLogos existed in the DB layer with zero callers.
  • Validation — checkLogoUrlIsImage HEAD-validates URLs before save (AbortController-timeout, body-cancel, file-viewer host blocklist). Catches Drive /view and Dropbox preview pages that silently return HTML.
  • Canonicalization — canonicalizeBrandDomain strips www./m./protocol/path on every save so kyber1.com and www.kyber1.com stop split-braining into separate registry rows. assertValidBrandDomain blocks garbage values.
  • Resolver fix — resolveBrandFromJson accepts the singular logo: {url} shape and the brand_colors alias used by some real-world brand.json publishers (e.g. house_portfolio variants). Brands declaring valid logos in those shapes were previously rendering empty.
  • UI fallback — logo <img> elements on the dashboard sidebar and member-profile page swap to the placeholder when the URL fails to load.
  • Auth — canReviewBrandLogos accepts the synthetic admin_api_key user so internal tooling can read pending logos via GET /api/brands/:domain/logos.

Refactor

Extracted shared logic into services/brand-identity.ts so the web PUT handler, the new member tool, and the existing admin tool all run identical transaction, validation, and canonicalization logic. Previously the same SQL was duplicated across three call sites with subtle drift.

Production data fix

Kyber1's www.kyber1.com brand_manifest was already corrected in production (Drive viewer URL → working S3 PNG) via the existing API. Philippe should see his logo on next page load.

Reviews

Ran the change through code-reviewer, security-reviewer, agentic-product-architect, and adtech-product-expert subagents. Applied feedback: AbortController-based timeout, response-body cancellation in the URL validator, canonicalizeBrandDomain used consistently across admin handlers, assertValidBrandDomain defense-in-depth, tool description disambiguation, member-facing error message softening (no ❌, less lecturing).

Out-of-scope follow-ups flagged by reviewers (filing as separate issues): brand-ownership transfer flow, pending-queue digest notification, verified-domain-owner auto-approve heuristic, attribute-context quote escaping in escapeHtml.

Test plan

  • npm run test:unit passes (832 tests, including 27 new ones across resolver and canonicalization helpers)
  • npm run typecheck passes
  • Production data fix verified via API (/api/brands/resolve?domain=www.kyber1.com returns the S3 PNG)
  • Reviewer to sanity-check Addie's tool selection on a synthetic prompt: "Hi, can you fix my logo?" should pick update_company_logo, not escalate
  • Reviewer to verify list_pending_brand_logos queue is non-empty in staging post-deploy

🤖 Generated with Claude Code

Two member escalations (thehook.es, kyber1.com) hit the same shape of
bug: saved logos either didn't render (broken Drive viewer URL stored
verbatim) or were stuck pending review with no admin path to triage.

Changes:

* Member self-service tool `update_company_logo` so a logged-in user
  can update their logo or brand color through Addie chat instead of
  escalating. Was previously admin-only via `update_member_logo`.
* Admin tools `list_pending_brand_logos`, `list_brand_logos`, and
  `review_brand_logo` so aao-admins can triage the moderation queue.
  `getPendingLogos` existed in the DB layer with no caller — pending
  uploads sat invisible.
* Wired `update_member_logo` and `update_member_profile` into the
  admin tool set; they were defined but unreachable from the router.
* `checkLogoUrlIsImage` HEAD-validates URLs (with body cancel and
  AbortController-based timeout) and rejects file-viewer hosts.
* `canonicalizeBrandDomain` strips www./m./protocol/path on every save
  so members no longer split-brain into separate `kyber1.com` vs
  `www.kyber1.com` registry rows. `assertValidBrandDomain` blocks
  garbage values from reaching the brands.domain column.
* `resolveBrandFromJson` accepts the singular `logo: {url}` shape and
  the `brand_colors` alias used by some real-world brand.json
  publishers. `referrals.ts` and `si-chat.ts` switched to the shared
  resolver instead of inline brands[0].logos[0] extraction.
* Logo `<img>` elements on the dashboard sidebar and member-profile
  page swap to the placeholder when the URL fails to load.
* `canReviewBrandLogos` accepts the synthetic `admin_api_key` user so
  internal tooling can read pending logos via the admin API.

Refactored shared logic into `services/brand-identity.ts` so the web
PUT handler, the new member tool, and the existing admin tool all run
identical transaction, validation, and canonicalization logic.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread server/src/utils/url-security.ts Dismissed
CodeQL re-flagged the SSRF rule on safeFetch's fetch calls when the
method/signal options were added to the call site. The same alert was
previously dismissed on main as "won't fix" because validateFetchUrl
already rejects private IPs, CGNAT, link-local, and IPv4-mapped v6 ranges
on every hop. Marking the call sites with lgtm[js/request-forgery] so
future edits don't keep tripping the analyzer.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread server/src/utils/url-security.ts Fixed
The lgtm[js/request-forgery] suppression isn't honored by GitHub Actions
CodeQL (it's an old LGTM.com-only format). Alert dismissed via the API
the same way as the previous one on main; explanatory comments stay so
future readers can see the validation contract without checking out the
security tab.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@bokelley
bokelley merged commit 1e8cb04 into main Apr 25, 2026
14 checks passed
@bokelley
bokelley deleted the bokelley/addie-skills-tools branch April 25, 2026 14:32
bokelley added a commit that referenced this pull request Apr 25, 2026
)

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

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]>

* Rebuild brand-claim challenge on WorkOS Domain Verification

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]>

* Address review feedback + fix Semgrep CI

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]>

* Code-quality cleanup from final review

* 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]>

---------

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.

2 participants