Skip to content

feat(widget): send the embed report and publish a readiness marker - #159

Merged
Ardnived merged 11 commits into
mainfrom
feat/embed-report
Aug 18, 2026
Merged

Ardnived merged 11 commits into
mainfrom
feat/embed-report

Conversation

@Ardnived

@Ardnived Ardnived commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • The embed report is actually sent. boot() took the payload and dropped it (void report), waiting on an endpoint that now exists. Two payload mismatches that would have 400'd every send are fixed — origin + pathname as separate fields, and mode: 'inline' — and mountKey no longer collapses a WordPress site on default permalinks onto a single mount.
  • A readiness marker lets SahajCloud verify an embed server-side. data-sahaj-atlas-ready on the host's <html>, carrying { v, routing, topLevel, urlWritable } — published only once the widget has genuinely booted, so a page whose widget failed cannot be adopted as a region's canonical URL.
  • Reporting on every load, not only on change. The differs-from-/clients/me gate made lastSeen useless as a liveness signal and cost a round trip on the load path; the server already collapses an unchanged report into no write for an hour.

Changes

  • src/loader/report.ts — mountParts splits the mount the way the endpoint takes it, preserves a WordPress ?p=<digits> and nothing else, and refuses what the server would refuse (non-http(s) documents, over-length paths) rather than 400ing on every load.
  • src/lib/readiness.ts — the marker's contract, kept a separate module from the send so its spec needs no mocks.
  • src/lib/embed-announce.ts — publishes the marker and sends the report. Separate from Widget.tsx because the one thing it guarantees (a refusal reaches the console, never the host's page) lives entirely in the wiring, which no pure test of the pieces can see.
  • src/App.tsx — AppShell publishes; the two widget-level boundaries clear. See "the placement is the guarantee" below.
  • src/lib/shape/routing.ts — MountDecision now carries the effective URL shape, so the marker attests what the router does rather than what a host asked for.
  • scripts/check-bundle-size.mjs — asserts the loader and embed graphs share no chunk.

Verification

  • Lint: ✓ (pnpm lint)
  • Types: ✓ (pnpm typecheck)
  • Tests: ✓ 1202 passing (pnpm test:run)
  • Build + size: ✓ (pnpm build, pnpm size — loader graph 3.0 KiB, unchanged from main)

Manual / visual verification

Driven through the real auto.js loader on a stand-in host page, against a local SahajCloud carrying the new endpoint. All four states re-checked after the final relocation:

Host page Widget Marker Report
Normal renders {"v":2,"routing":"query","topLevel":true,"urlWritable":true} 200, pathname: "/"
?p=321 renders published pathname: "/?p=321"
?p=321&utm_source=ads renders published pathname: "/" — permalink refused whole
Loader URL with no key "isn't set up correctly" absent not sent
Host CSP omits the API origin "servers are having trouble" cleared blocked

The host's ?utm_source=… never appears in a payload. A refusal (a 404 from a SahajCloud without the endpoint) produced [sahaj-atlas] could not record this embed … (mount: …) in the console and left the widget working.

Notes for reviewer

The placement of the announce is the guarantee, and it is not obvious. The natural home is the widget root. That is wrong: componentDidCatch runs in the commit's layout phase and a parent's useEffect in the passive phase after it, so a synchronous first-render failure — a loader URL with no key, the most likely host mistake — let the boundary clear a marker not yet published, and the root's effect then published one over the error screen, permanently. Called from AppShell instead, the marker cannot precede a successful boot, is never published over the loading state, and re-publishes when "Try again" recovers. src/lib/announce-site.test.ts pins the location the way href.test.ts pins the app's three anchors.

A shared chunk crept between the loader and the widget. One value import from @/loader/report, for a one-line string join, made that module reachable from both build entries — so rolldown factored it into a chunk both auto.js and embed.js statically import, i.e. an extra request on the loader's critical path on every host page view. src/loader/literals.ts predicts exactly this and its whole enforcement was that docblock. Fixed, and pnpm size now names the mistake; verified by reintroducing the import and watching the build go red.

Two things deliberately NOT done, both worth a follow-up:

  1. payload-types.ts is not regenerated, though the issue mentions it. pnpm types:cms pulls whatever is on SahajCloud main, and today that includes a rename of the registration question set (priorExperience/referralSource/healthInfo/accessibility/guests → experience/referral/aspirations/questions). It breaks the build in four places and moves a live form and its locale keys with it — its own ticket. The acceptance criterion itself (legacyConfig out of ClientSchema and the /clients/me select) is done.
  2. The 50-mount cap is now cheaper to exhaust — reporting per page load rather than per fingerprint change means any visitor can file 50 distinct mounts (a site-wide snippet, an SPA catch-all, 50 ?p=<n> values) and leave an operator unable to nominate the page they want. The fix belongs server-side in feat(access): add embed metadata and canonical ownership to Clients SahajCloud#633 — evict least-recently-seen, or count only verified mounts, rather than first-50-wins.

One type, not two. EmbedReport was EmbedFingerprint & MountParts — a strict superset of the type it sat beside on the boot singleton, so topLevel/urlWritable existed twice with nothing keeping them in agreement (they couldn't diverge, but only because boot() got both from one detect() call). The join now happens once, at the transport, as EmbedReportBody. Two things fall out of that: the wire shape is stated rather than being whatever a domain type happened to hold, so a field added to the fingerprint can't silently start being sent; and the mount is read at send time rather than composed on loader idle and carried — which is what made it name the page the widget first loaded on, and keep naming it after a host SPA had navigated away. src/loader/report.ts is gone with it: the loader no longer touches the host's URL at all, and its graph drops 3.0 → 2.9 KiB.

The trap in merging them, which is asserted: a page with no reportable mount — a blob: document, an over-long path — still has a widget that booted, so it loses the report and keeps the marker.

One deliberate asymmetry: the report's routing is what was configured; the marker's is what the router does. routing=path is accepted without being honoured, so those differ — which is exactly the nominate-vs-decide split SahajCloud describes. canonicalViable no longer takes the host's word for it either: it previously exempted routing=path from the paramPersisted requirement, which let any host set the one judgement in the payload for a mount that query-routes anyway.

Closes #153

🤖 Generated with Claude Code

Ardnived and others added 10 commits August 18, 2026 11:29
`POST /api/clients/report` takes `origin` and `pathname` as separate fields and
spells the inline mode `inline`, so the payload this shipped with 400s on every
send. The split is not cosmetic: the endpoint refuses a path carrying a query
string, and it can only enforce that if the path arrives on its own.

`mountKey()` discarded the whole query, which collapses a WordPress site on
default permalinks onto one mount — every post reports as `https://site.com/`,
and the page an operator has to name as canonical cannot be named at all. The
endpoint now permits `?p=<digits>` and nothing else, so the widget preserves
exactly that and still drops everything a seeker could have put there,
`?p=123&utm_source=…` included.

`fingerprintChanged` goes with the differs-from-/clients/me gate it existed for.

Refs #153

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`boot()` took the payload and dropped it, waiting on an endpoint that now
exists. Two things had to be true before switching the send on.

The send waits for a mount. A report filed when the bundle arrives attests to a
widget that has not rendered and might never, and the marker paired with it
would be worse than nothing: SahajCloud verifies an embed by loading the host
page itself and reading `data-sahaj-atlas-ready` off the rendered DOM, so a
marker written on script load turns verification into theatre. Both fire from a
mount effect instead, once per owned element.

The marker publishes the routing the router ACTUALLY uses, not the routing
somebody configured — `routing=path` is still accepted without being honoured,
and the verifier builds canonical URLs from this field.

It goes over the DOM rather than a `postMessage` because the Browser Rendering
API returns DOM and has no message channel, and an injected listener would race
the widget's boot — failing healthy sites, the one outcome a verifier must never
produce.

Closes #153

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A refusal from the endpoint must reach the console rather than the host's page,
and that guarantee lives entirely in the wiring — a `.catch` that was never
attached looks exactly like one that was, to every pure test of the pieces.
`.claude/rules/tests.md` records the last time that gap shipped.

So the announce is its own module: importing Widget.tsx to exercise it would
drag mapbox-gl, vaul and every eager view into the node lane, which is the same
argument strip-label.ts already makes.

Refs #153

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
SahajCloud removed the field. It was `.nullish()` and never read for behaviour,
so this is dead weight — but it is also the thing `src/loader/detect.ts` exists
to replace: a hand-maintained `routing_type`/`embed_type` beside what the widget
observes is a second, contradictory source for the same facts, and the legacy
values are wrong in the field.

`payload-types.ts` is deliberately NOT regenerated here. `pnpm types:cms` pulls
whatever is on SahajCloud main, and today that includes a rename of the
registration question set — `priorExperience`/`referralSource`/`healthInfo`/
`accessibility`/`guests` collapsing into `experience`/`referral`/`aspirations`/
`questions` — which breaks the build and moves locale keys and a live form with
it. That is its own ticket, not cargo on this one.

Refs #153

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Both are host-observable, so the integrator guide is where they become real: a
new attribute on their <html>, a request per page load, a WordPress `?p=` that
now survives, and two refusals that are configuration rather than a fault in
their page.

The #149 changelog entry claimed the widget reported. It observed and then
dropped the payload, so no host has ever seen a request from it — the entry is
corrected rather than left to contradict this one.

No CSP change: the endpoint is on the API origin every host already allows, and
the table now says so where somebody would look for it.

Refs #153

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The important one: a single value import from `@/loader/report` for a one-line
string join made that module reachable from both build entries, so rolldown
factored it into a chunk BOTH auto.js and embed.js statically import — a fourth
request on the loader's critical path, on every host page view, for 0.2 KiB.
That is exactly what `src/loader/literals.ts` predicts, and its whole
enforcement was that docblock: `pnpm size` only checked for `embed.js` itself,
so nothing failed. The import is gone and the gate now names the mistake —
verified by reintroducing it and watching the build go red.

The once-per-page flag moves into `embed-announce.ts` behind
`releaseAnnouncement()`. It was in Widget.tsx, which has no spec, while the
module it belongs to exists precisely because a wiring guarantee needs one — so
"one POST per page" is now asserted rather than hoped for, and
`releaseOwnership` delegates instead of poking another module's state.

The attested routing comes from `MountDecision` rather than a ternary in
Widget.tsx that was provably the constant 'query'. `mountDecision` already owns
"path is accepted and not honoured"; now it says so in a field instead of
leaving each consumer to re-derive it.

The response schema drops `mount`/`stored`. Nothing reads them, and pinning a
field we never read would turn a harmless CMS rename into a "could not record
this embed" warning on every host's console — a worse failure than the drift it
would detect. `ok` is the receipt, as it is for contactAdmin.

The POST now waits for idle. It has no deadline and shared a mount with the
three fetches the visitor is actually waiting for, all to one origin.

Refs #153

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Three repo-facing docs the branch changes:

- `.claude/rules/data-layer.md` — `reportEmbed`, and why its response schema is
  narrower than the parse-everything rule the other two mutations follow.
- `.claude/rules/components.md` — the readiness marker is the one thing the
  widget writes onto the host's own <html>, so the exception is argued where the
  "scope everything to our subtree" rule lives.
- `CLAUDE.md` — `pnpm size` now also asserts the loader and embed graphs share
  no chunk, and the note says why a byte budget could never have caught it.

Refs #153

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
From the code-review pass. All four are the marker or the report claiming
something that is not true.

**The marker survived a failed boot.** The effect fires when the wrapper
commits, but App's Suspense and error boundary are inside that wrapper — so a
host whose CSP omits the API origin got "could not be loaded" on screen with
`data-sahaj-atlas-ready` still on their <html>, and SahajCloud's verifier would
adopt that page as a region's canonical URL. The two boundaries that replace the
whole widget now take the marker down; a drawer failing is a widget that still
works, and over-clearing spends a strike against the verifier's three-failure
budget.

**A re-mount re-filed a stale mount.** `auto.js` does not run again on a host
SPA's client-side navigation, so `embed.report` keeps naming the page the widget
first mounted on. Resetting the flag on release meant a later element re-POSTed
that old mount and kept its `lastSeen` warm — answering the one question the
record exists for with the wrong page. The report is now once per page load and
the reset is gone; the marker still re-publishes, because a re-mounted widget
does have something true to say.

**The idle wait outlived the teardown grace.** The deadline was 2s against a 1s
grace that nulls the API key, so an element removed shortly after mount fired an
unauthenticated POST and the catch blamed the host's allowed-domains list for
our race. The deadline is now 500ms, below the grace by construction.

**`await whenIdle()` sat outside the try**, so a host that patched
`requestIdleCallback` — consent managers and perf shims do — turned a diagnostic
of ours into an unhandled rejection in their page. A shim that never calls back
was the quieter version: no report, ever, with the flag already spent. The wait
is inside the try and the deadline runs on both paths.

Also: `mountParts` now refuses what the endpoint would refuse — a non-http(s)
document (a `blob:` URL yields a pathname with no leading slash) and a path past
the column's 512 chars. Either was a 400 on every single load of that page.

Refs #153

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
From the security review, which proved the ordering empirically rather than
reasoning about it: `componentDidCatch` runs in the commit's layout phase and a
parent's `useEffect` in the passive phase AFTER it. So the marker's takedown
could not protect it. A loader URL with no `key` makes AppShell throw during its
first render; the boundary caught, cleared a marker that had not been published
yet, and the widget root's effect then published one over the "could not be
loaded" screen — permanently. The most likely host mistake there is, producing
the exact false attestation this feature exists to prevent.

The announce moves into AppShell, below the app boundary and below the Suspense
read of the client record. Three properties then hold together, none by luck:
the marker cannot precede a successful boot (the widget demonstrably reached the
API), it is never published over the loading state, and "Try again" remounts
AppShell and re-publishes what the boundary took down — which the old placement
never did, since the reset remounts AppShell rather than the root.

`announce-site.test.ts` pins that location the way href.test.ts pins the app's
three anchors, because the placement is the guarantee and no pure test of the
pieces can see it.

`canonicalViable` stops exempting `routing=path` from the paramPersisted
requirement. `routing` comes off the host's own script URL while `mountDecision`
hard-codes the effective shape to query, so the exemption let any host turn the
one judgement in the payload on for a mount whose `?atlas=` their router eats —
with no server-side evidence able to contradict it, since the endpoint stores no
`canonicalViable`. Restore it when path routing is actually honoured.

Also corrects readiness.ts's framing: the marker detects a BROKEN embed, not a
forged one. It has no nonce or signature and every field comes from an API a
host can patch, so `allowedDomains` is the trust boundary — worth stating where
someone would otherwise read more into it.

Refs #153

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Refs #153

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Aug 18, 2026 •

Copy link
Copy Markdown

Deploying sahajatlas with  Cloudflare Pages  Cloudflare Pages

Latest commit: 9a33f7f
Status: ✅  Deploy successful!
Preview URL: https://f6017d07.sahajatlas.pages.dev
Branch Preview URL: https://feat-embed-report.sahajatlas.pages.dev

View logs

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Aug 18, 2026 •

Copy link
Copy Markdown

Deploying sahajatlas-design with  Cloudflare Pages  Cloudflare Pages

Latest commit: 9a33f7f
Status: ✅  Deploy successful!
Preview URL: https://a1925187.sahajatlas-design.pages.dev
Branch Preview URL: https://feat-embed-report.sahajatlas-design.pages.dev

View logs

`EmbedReport` was `EmbedFingerprint & MountParts` — a strict superset of the
type it sat beside on the boot singleton, so `topLevel` and `urlWritable` existed
twice with nothing keeping them in agreement, and the marker read one copy while
the server got the other. They could not diverge in practice, because `boot()`
received both from one `detect()` call, but only by construction rather than by
anything the types said.

The join moves to the transport, where a payload belongs. `EmbedReportBody` in
`mutate.ts` is now the only place the two halves meet, and `announceEmbed`
spreads them explicitly — so the wire shape is stated rather than being whatever
a domain type happened to hold, and a field added to the fingerprint cannot
silently start being sent.

That lets the mount be READ rather than carried, which fixes something the flag
was papering over: it used to be composed on loader idle and held until the
widget mounted, so it named the page the widget first loaded on and kept naming
it after a host SPA had navigated away. `currentMount()` reads the URL at the
moment of sending. The once-per-page-load bound stays, but it is now a volume
decision about the 50-mount cap rather than a correctness one.

`src/loader/report.ts` is gone: with the composition moved, the loader has no
business with the host's URL at all, and `boot()` loses its third parameter. The
loader graph drops 3.0 → 2.9 KiB.

The one asymmetry that survives, and the trap in merging these at all: a page
with no reportable mount — a `blob:` document, an over-long path — still has a
widget that booted, so it loses the report and keeps the marker. Asserted.

Refs #153

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@Ardnived
Ardnived merged commit 698d11d into main Aug 18, 2026
5 checks passed
@Ardnived
Ardnived deleted the feat/embed-report branch August 18, 2026 21:28
Ardnived added a commit to sydevs/SahajCloud that referenced this pull request Aug 18, 2026
Two defects that would each have broken this endpoint in production.

**Every report would have 400'd.** The widget shipped in sydevs/SahajAtlasWeb#159
sends `origin` and `pathname` as separate fields and spells the inline mode
`inline`; this took a single `url` and expected `script`. The split is not
cosmetic — it is what lets the path be checked on its own.

**Every successful report would have hung.** The usage plugin increments
`usage_daily_requests` on the caller's own `clients` row, on its own connection,
for the very request being served, while `payload.update` held that row inside
the request transaction. Both sides sit on `Lock: transactionid` and the request
never returns. Replaced with a single autocommit `jsonb ||` merge through the
same pg-pool seam the usage counters use, which also closes the
read-modify-write window.

Also: a reported path may now carry a WordPress `?p=<digits>` permalink and
nothing else. Discarding the query collapses a default-permalink site onto one
mount — every post reports as `https://site.com/` — leaving the page an operator
must name as canonical unnameable, for exactly the audience this feature targets.

Refs #633

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Ardnived added a commit to sydevs/SahajCloud that referenced this pull request Aug 19, 2026
…635)

* feat(clients): add embedMetadata + canonical ownership fields

The Sahaj Atlas white-label program needs two things on a client: a place
for the embed to report what it observed about the page it is installed
on, and an explicit, uniqueness-enforced statement of which region a
client owns the canonical URLs for.

Data only — `canonical.enabled` defaults false, nothing resolves
differently, and no `webUrl` changes.

- `embedMetadata` (json, admin-readonly) keyed by origin + pathname, so a
  site with several embeds accumulates a record per mount. A JSON column
  because nothing queries it: the ownership resolver loads every client
  with `pagination: false` (~31 rows) and filters in memory. Wired to a
  JSON Schema, so Payload both generates the type and rejects a malformed
  write.
- `canonical` group — `enabled` (default false), `domain` (bare host,
  deliberately not derived from the multi-valued `allowedDomains`),
  `mount` (may carry a query string; WP default permalinks are `/?p=123`)
  and `routing` (`query` | `path`, never `hash`).
- `validateCanonicalOwnership` requires a region + domain when enabled,
  and rejects a second enabled client on a region, naming the incumbent —
  `region` alone cannot identify an owner (3 published clients map to
  Czechia, 2 to Finland, 2 to Australia).
- `POST /api/clients/report` writes it. `clients` is excluded from the
  usage plugin, so origin enforcement is called by hand; the reported
  mount's host is checked against `allowedDomains` too.
- `legacyConfig` removed rather than promoted: a second, contradictory
  source of routing_type/embed_type beside the new fields is how they
  drift, and the legacy values are unverified (`sahajayoga.at` is recorded
  as `script` and in fact serves an iframe).

Refs #633

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

* docs(openapi): register POST /api/clients/report in the shim

Mandatory per .claude/rules/endpoints.md. The request schema sources its
`mode` / `routing` enums and its `url` bound from the collection's own
constants, so they can't drift from the Zod schema in the handler.

It stays `x-internal` in the filtered spec — `clients` is in
ALWAYS_HIDDEN_COLLECTIONS and in no project — which is the right outcome
for the first-party widget's telemetry channel. Pinned by a test so a
future filterSpec change can't publish it by accident.

Refs #633

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

* feat(scripts): seed canonical.domain/routing from the legacy Atlas config

A starting point, never a decision — `canonical.enabled` is left false on
every row, because the legacy values are unverified.

Reads `legacyData.config`, the verbatim import record kept by
`legacyMigrationFields()`, rather than the `legacyConfig` column this
ticket drops. Same values (the importer copied one from the other), and
reading the surviving one means the script works whether it runs before
or after the deploy that applies the migration — migrations auto-apply
in-process on Railway boot, so a script needing the dropped column could
never be run in time.

Dry run by default, `--force` to write, re-runnable: it only ever fills a
field that is currently empty, so a hand-set value outranks the legacy
one and a second pass finds nothing to do.

Refs #633

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

* chore(migrations): add client canonical columns, drop legacy_config

Split into two migrations on purpose. Generated as one, drizzle sees
`legacy_config` dropped alongside `canonical_enabled` added in the same
table and raises its rename-vs-create prompt — which hangs on non-TTY
stdin and, answered wrong, would rewrite the column instead of dropping
it. Additive-then-destructive gives each migration an unambiguous diff,
so both generate non-interactively and read clearly in review.

Both cover `clients` and `_clients_v` (drafts are on), and both are
reversible.

The dropped `legacy_config` is not a data loss: the importer copied it
from `legacyData.config`, which is untouched, and that is what
`scripts/backfill-client-canonical.ts` reads.

One thing the generated SQL settled: `canonical_routing` ships
`DEFAULT 'query'`, and Postgres backfills that onto every existing row —
so "the field is empty" can't gate the routing seed, and the backfill
would have skipped the single legacy client on `path`. It now seeds
routing whenever the legacy value differs, which is safe because it
already refuses to touch a client that opted in. `domain` keeps the
fill-only-when-empty rule, since that one is typed by hand.

Refs #633

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

* test(clients): cover the embed-metadata merge and mount-key rules

Pure-function coverage for the two things the endpoint delegates every
decision to: mount-key validation (query/fragment/scheme/credentials
refusals, and that two spellings of one page collapse to one key) and the
keyed merge (two pages produce two keys, the freshness window suppresses
a repeat write, a malformed sibling is repaired, the cap evicts
least-recently-seen but never the mount just reported).

Plus a compile-time pin that the hand-written record type and the field's
JSON Schema agree. Verified by mutation: adding a field to
EmbedMountRecord that the schema doesn't declare fails
`pnpm typecheck:tests`.

Refs #633

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

* test(clients): cover canonical ownership, the report endpoint, backfill

One Payload bootstrap, three surfaces.

The ownership hook: each rejection asserts the message a human actually
reads (Payload keeps the generic summary on `.message` and the per-field
text on `.data.errors[]`, which is what the admin renders under the
field), including that the incumbent is named. Also covers the case the
hook nearly missed — moving an already-enabled client onto an owned
region, which is why it watches `region` and not just `canonical`.

The endpoint: refuses a draft caller, an Origin outside allowedDomains, a
reported host outside it, and a url carrying a query string or fragment;
two pages of one site round-trip through the DB as two keys; a repeated
identical report is proven not to write by the row's own `updatedAt`
rather than by the response body.

The backfill: seeds from `legacyData.config`, never opts a client in,
leaves a draft a draft (a disabled Atlas service must stay unable to
authenticate), doesn't overwrite a hand-set domain, and is idempotent.

And the ticket's data-only claim, asserted directly: an event's `webUrl`
and `webPath` are unchanged by enabling canonical ownership on a client
that owns its region.

Refs #633

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

* docs(rules): document canonical ownership + the embed report endpoint

api-clients.md gets the field contract and the three things about
`POST /api/clients/report` that aren't obvious from the handler: `clients`
is excluded from the usage plugin so both origin enforcement and usage
tracking are the handler's own problem; the reported url's host is
checked against `allowedDomains` on top of the request's Origin; and
"rate limiting" here is Cloudflare's edge limit plus a no-op-on-unchanged
write, since the app-level hook is a no-op on Railway.

Also records the two decisions a reader will otherwise re-litigate: why
canonical.domain isn't derived from allowedDomains, and why canonical
identity stays a human's call while viability is automatic.

Refs #633

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

* refactor(clients): move shared client vocabulary to src/lib/clients

Per /simplify's altitude + reuse passes.

Altitude: `canonical.ts`, `embedMetadata.ts` and `backfillCanonical.ts`
sat in the collection folder while being imported by the OpenAPI plugin
and an operator script — the exact cross-owner internal import rule 4 of
project-structure.md prohibits. Before this branch, nothing in the repo
imported from `src/collections/` into `src/plugins/` or `scripts/`; these
three were the first. They're pure vocabulary and pure functions with no
Payload dependency, so `src/lib/clients/` is their home, alongside
`src/lib/schedule/` which exists for the same reason. No barrel — the
consumers cherry-pick, as with `schedule/`.

Reuse: `normalizeCanonicalDomain` was a second URL normalizer beside
`normalizeHost` in the origin-enforcement helpers. It now delegates. The
one behaviour it must not inherit — `normalizeHost` preserves a `*.`
wildcard label, which a canonical domain must never be — is rejected for
free by CANONICAL_DOMAIN_PATTERN, whose character class has no `*`.

Not taken: the pass also flagged `parseAllowedDomains` running twice per
report (once inside `assertClientOriginAllowed`, once for the reported
mount's host). Deduplicating it means inlining that helper's logic — the
preview-secret bypass, the missing-origin allowance, the WARN log — which
trades a duplicated security rule for one `split` on a two-line textarea.

Refs #633

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

* fix(clients): reject an unparseable lastSeen and a full-URL mount

Two findings from the code-review pass.

`lastSeen` is the eviction sort key, and `sanitizeEmbedMetadata` only
checked it was a string. A corrupt stamp therefore survived into
`evictOldest`, whose comparator would return NaN — which does not sort
that record last, it corrupts the ordering of the whole array and evicts
arbitrary mounts. Rejecting it at the sanitize layer removes the cause
rather than patching the comparator, and matches what that layer already
promises for every other field: drop the bad record, repair on next write.

`canonical.mount` accepted any text, so an operator could paste
`https://host:8080/path` into it. The host is stated once, in
`canonical.domain`, so the resolver would have joined the two into a URL
resolving nowhere. It now requires a leading `/` — which still accepts
`/?p=123`, the WordPress default permalink this field exists for.

Also documents, at the hook, that the one-owner-per-region rule is
check-then-write: two simultaneous admin saves could both pass. Left
undefended on purpose (human-paced writes, visible rather than silent
result); the airtight fix is a partial unique index Payload can't declare,
and the note says where to add it if the resolver needs the invariant.

Not taken: a claim that the backfill skips the routing seed when
`canonical.routing` is unset. It's inverted — `'query' !== undefined` is
true, so that is exactly the case that seeds.

Refs #633

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

* fix(clients): match the shipped widget, and merge reports atomically

Two defects that would each have broken this endpoint in production.

**Every report would have 400'd.** The widget shipped in sydevs/SahajAtlasWeb#159
sends `origin` and `pathname` as separate fields and spells the inline mode
`inline`; this took a single `url` and expected `script`. The split is not
cosmetic — it is what lets the path be checked on its own.

**Every successful report would have hung.** The usage plugin increments
`usage_daily_requests` on the caller's own `clients` row, on its own connection,
for the very request being served, while `payload.update` held that row inside
the request transaction. Both sides sit on `Lock: transactionid` and the request
never returns. Replaced with a single autocommit `jsonb ||` merge through the
same pg-pool seam the usage counters use, which also closes the
read-modify-write window.

Also: a reported path may now carry a WordPress `?p=<digits>` permalink and
nothing else. Discarding the query collapses a default-permalink site onto one
mount — every post reports as `https://site.com/` — leaving the page an operator
must name as canonical unnameable, for exactly the audience this feature targets.

Refs #633

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

* feat(clients): pick a verified embed instead of typing three fields

Replaces `canonical.domain` / `.mount` / `.routing` with one choice — which of
the embeds this service actually reported owns its canonical URLs — and has the
CMS confirm that choice by loading the page itself.

Three hand-typed fields were sized for ~31 services we configured. The client
base is growing sharply and most of those users are not technical; three fields
are three chances to name a URL that points nowhere, with nothing to say so.

- `canonical.embed` — the nomination, chosen from a picker
  (`CanonicalEmbedPicker`) whose description renders the finished sample URL,
  including the `&` join a WordPress `?p=` mount needs.
- `canonical.verification` — job-written only, from what was observed on the
  live page. Reports nominate; the server decides. Deriving routing from reports
  would let a forged report reshape a live canonical URL.
- `canonical.nextVerifyAt` — an indexed column, so the job keeps the cheap
  single-predicate query `ExpireEvents` uses.
- `lib/embedVerification/` + `jobs/VerifyEmbeds` — Cloudflare Browser Rendering,
  the readiness-marker parser, and the nightly ladder. Three consecutive
  *definitive* failures disable ownership and notify; `inconclusive` (provider
  error, quota, bot challenge) never counts, because auto-disabling a working
  canonical changes live public URLs for no reason.
- `POST /api/clients/:id/verify-embed` — the same routine on demand, so setup is
  not gated on the cron. It never disables: three strikes is a judgement about a
  pattern over days.

Tabs regrouped Config / SEO / Access, with the reported embeds collapsed beside
the setting they inform. `required` on `embed` plus the `enabled` condition is
exactly "required when canonical ownership is on" — the same shape as
`primaryContact`, and an integration test pins that a disabled service still
saves with no embed through a plain API write.

The legacy backfill is deleted: canonical now requires a *verified reported*
embed, which legacy Atlas config can never produce. Both canonical migrations
were regenerated to emit the final shape rather than add-then-drop, since
neither has been applied anywhere.

Refs #633

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

* docs(rules): record the picker, verification, and two CLI traps

- api-clients: rewrites the canonical section for the picker model, adds how a
  nomination becomes a canonical URL, and states plainly what the readiness
  marker proves (a broken embed) and what it does not (a forged one) — the
  obvious reading of "server-attested" is too strong. Also records why the report
  write is raw SQL and why the body is two fields.
- openapi: request schema follows the widget's `origin` + `pathname` split, with
  the guard asserting it so the two cannot drift apart again.
- migrations: never generate with `E2E_TEST=true` — it disables the usage plugin,
  so the snapshot loses `resetUsage`/`trackUsage` and a later migration tries to
  re-add a label that has existed since the initial schema, aborting the boot
  migration. It is tempting precisely because it is the workaround for the
  ethereal outage that kills the CLI. Also: `generate:types` silence means "no
  change", not "done".
- storage: `CLOUDFLARE_API_KEY` now also carries Browser Rendering, and losing
  that permission degrades to a silent `not-configured`.

Refs #633

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

* fix(build): keep pg out of the admin client bundle

The Railway deploy failed with `Module not found: Can't resolve 'dns'`. The
canonical picker is a client component; it imports `@/lib/clients/canonical`,
which imported the `@/plugins/usage` barrel, which re-exports the pg-pool seam —
so `pg` was pulled into the browser bundle.

Nothing local caught it. It type-checks, lints, and passes every test, because
**GitHub Actions does not build this app** — Railway does. Reproduced both ways
before and after the fix: `pnpm build` fails with six module-resolution errors on
the barrel import and succeeds on the deep one.

`tests/unit/client-bundle-safety.spec.ts` walks the real import graph from each
admin client entry point so this cannot regress silently again. It carries its
own control — the report endpoint legitimately uses the pg seam and must be
flagged — so the walk can't pass vacuously.

Refs #633

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

* feat(clients): exercise Browser Rendering for real, and classify on its codes

The verifier had never touched Cloudflare — every test stubbed the render — so
the request shape, the auth header, and the error patterns were assumptions.
Driven against the live API they turned out right in shape and wrong in method.

`classifyRenderError` now keys on Cloudflare's numeric codes, captured live:
`6002` selector timeout, `5006` network/DNS, `10000` auth. Prose matching stays
as the fallback for codes we have not met, but it cannot be the primary rule —
a dead customer domain returns `Network connection closed.`, which says nothing
on its own and only classified correctly because the pattern happened to include
"connection". The real payloads are pinned in the unit tests.

`5006` counts as a real failure even though Cloudflare's own detail says it "can
also happen" for other reasons. Detecting dead domains is the main thing this job
exists for, and three-consecutive-failures is what makes that safe: a blip does
not repeat on three separate nights.

`verifyEmbed` now refuses any non-http(s) mount before rendering. `canonical.embed`
is normally a picker option, but it is a plain text field an admin can type into,
and that is the point where a string becomes an outbound page load — `data:`,
`file:` and `javascript:` have no business reaching a browser.

`scripts/verify-embed-live.ts --self-test` drives all four outcomes against the
live API in ~20s, so the integration can be re-proven after any change, and a
disabled canonical can be diagnosed by running its URL through the same path the
job takes.

Refs #633

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

* ci: stop installing a browser the smoke lane never launches

The job was cancelled at 25 minutes with no explanation. It was the
`timeout-minutes` cap: `playwright install --with-deps chromium` ran for 18m22s,
and a GitHub job timeout reports as *cancelled* rather than failed, so nothing
said why.

The install was never needed. Every smoke spec uses only the `request` fixture
(`APIRequestContext`), which is plain Node HTTP — nothing launches Chromium,
despite the `chromium` project name in the config. Verified by running the whole
suite with `PLAYWRIGHT_BROWSERS_PATH` pointed at an empty directory: all six
specs issued real requests and failed on an application error, not a missing
browser.

Two related things this surfaced:

- **A skipped smoke lane looked identical to a passing one.** When no preview is
  discovered both steps skip and the job stays green, so "Lint, Test & Smoke:
  pass" could mean smoke never ran — which is what happened on the previous
  commit, where discovery polled for 12 minutes and then gave up. CI now emits a
  `::warning` saying so.
- **The budget was structurally impossible.** Discovery alone allows 12 min for
  the deploy plus 5 for health; with ~6 min of tests that is 23 of the 25-minute
  cap before smoke starts. Raised to 30 for headroom.

Refs #633

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

* docs(migrations): regenerating a deployed migration poisons its preview

I regenerated the canonical migrations to emit their final shape, saying neither
had been applied anywhere. That was wrong: Railway builds a preview environment
on every PR push and runs `prodMigrations` on boot, so both had already run —
four times. The preview kept the old migration's columns with no row naming the
new one, so it re-ran and died on `column "canonical_enabled" ... already
exists`, crash-looping the app and 502-ing every route.

The clean-database migrate test passed precisely because it was clean; the
failing state needs a database that ran the old migration.

Writes up the rule, both remedies (reset the environment, or stack a migration
instead of regenerating), why `ADD COLUMN IF NOT EXISTS` is the wrong escape
hatch, and how to read PR-preview logs at all — a Railway *project* token only
sees production, so the CLI's user session is the only way in.

Refs #633

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

---------

Co-authored-by: Claude Opus 5 (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.

feat(widget): send the embed report and publish a readiness marker

1 participant