Skip to content

fix(widget): survive foreign hashes and harden the mount path - #112

Merged
Ardnived merged 11 commits into
mainfrom
fix/widget-mount-hardening
Aug 7, 2026
Merged

Ardnived merged 11 commits into
mainfrom
fix/widget-mount-hardening

Conversation

@Ardnived

@Ardnived Ardnived commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Summary

  • A host URL carrying any anchor no longer renders a blank widget. #respond, #comment-123, #contact — routine on WordPress — were read by react-router as a location outside the ! basename, so it rendered null. The widget now recognises that the fragment isn't its to take, routes in memory instead, and leaves the host's anchor (and its on-load scroll) completely alone.
  • Mounting no longer pushes a host history entry. The boot write was window.location.hash = …, an assignment, so the visitor's first Back press appeared to do nothing — contradicting the "never pollute host history" contract dismissAction otherwise honours. It is a replaceState now, absolutised against the current location so a host <base href> can't redirect it.
  • Two host mistakes stop being silent: a second copy of the embed script no longer throws NotSupportedError, and a second <sahaj-atlas> element no longer runs on the first one's API key and theme root — it is refused before it mounts, with a console warning.
  • A throw from Providers/BrandTheme no longer blanks the widget, and the embedded subtree finally carries lang, a landmark role and a localized name. og:locale stops being written into the host's <head>.

Changes

  • src/lib/shape/hash.ts (new) — mountRoute(hash, basePath), the pure three-way decision: ours (a real #!… route wins over base-path), free (unclaimed, or an #!… path safePath rejects — ours to normalise), foreign (the host's anchor, never touched). Composes with the existing safePath guard, so #!//evil.example and #!javascript:… are normalised away rather than routed.
  • src/Widget.tsx — acts on that decision; HashRouter or MemoryRouter, decided once; a customElements.get guard; a subclass that enforces one element per page in connectedCallback; lang / role="region" / aria-label on the theme root.
  • src/App.tsx — RootBoundary above Providers/BrandTheme with a static, translation-free, inline-styled fallback that reads none of the things that can be what failed; og:locale gated to standalone.
  • src/lib/report.ts — reportIntegrationWarning, the sibling of reportInternalError, so host-integration mistakes reach the same seam a real reporter will wire into.

Verification

  • Lint: ✓ (pnpm lint)
  • Types: ✓ (pnpm typecheck)
  • Tests: ✓ 613 passing (pnpm test:run) — 31 of them new, across hash.test.ts (node) and hash.router.test.tsx (jsdom)
  • Build: ✓ (pnpm build); both guards confirmed present in the minified dist/embed.js

Two defects found by /code-review and /security-review were reproduced against the real dependencies before fixing, not reasoned about:

  • react-router writes #/!/gb/london, not #!/gb/london — it normalises the basename ! to /!. The first version of the classifier only knew the boot spelling, so any reload after an in-widget click would have been misread as the host's anchor. Caught by mounting a real HashRouter; hash.router.test.tsx now pins the round trip in both directions.
  • @r2wc/core sets its connected flag in its constructor, so attributeChangedCallback mounted the React root before connectedCallback could refuse it. Probed against @r2wc/[email protected] with a fake renderer: MOUNT, connectedCallback, UPDATE, MOUNT, connectedCallback, REFUSED. After the fix: connectedCallback, MOUNT(api-key intact), connectedCallback, REFUSED.

Manual / visual verification

Browser verification was not run (a parallel agent owned the shared browser this wave). demo.html gained an #respond anchor target so #1 is reproducible. Please run:

  1. Foreign anchor. Load demo.html#respond. Expect: the widget renders (not blank); location.hash is still #respond; window.scrollY > 0 and #respond is at the top. Repeat with #comment-123 (no matching element — the widget must still render).
  2. Clean URL, no history entry. Load demo.html, wait for the widget, press Back once. Expect: you leave the page entirely (previously the first press only undid the widget's own hash write). Check the URL reads #! and that history.length did not grow.
  3. Deep link still wins. Load demo.html#!/gb/london, then click into a region and reload. Expect: the reloaded page shows the same region, not the root — this is the #/!/… round trip the jsdom spec covers, confirmed in a real browser.
  4. Double script include. Add a second <script src="http://localhost:4173/embed.js" type="module">. Expect: no NotSupportedError; one console warning [sahaj-atlas] <sahaj-atlas> is already defined…; the widget works.
  5. Two elements. Add a second <sahaj-atlas api-key="…">. Expect: the first renders normally, the second renders nothing, one warning [sahaj-atlas] only one <sahaj-atlas> runs per page…. Confirm the first widget's theme and API key are unaffected.
  6. Forced provider throw. Temporarily throw new Error('boom') at the top of BrandTheme. Expect: the static "Sahaj Atlas could not be loaded. Please reload the page." rather than an empty area, plus a [sahaj-atlas] widget root console error.
  7. Language announcement. With locale="fr", confirm the widget root has lang="fr" and role="region" with a French aria-label, and spot-check in VoiceOver that the landmark is exposed and pronounced in French. role on a display: contents element is the part worth actually checking — WebKit has historically dropped those from the a11y tree.
  8. Host <base href>. On a page with <base href="/blog/">, confirm the mount write only changes the fragment and leaves the path and query intact.

Notes for reviewer

  • The multi-instance decision the issue left open: console.warn + no-op, not an on-page notice. A second element is a host misconfiguration, and injecting untranslated developer copy into somebody's public page is worse than putting it where the integrator is already looking. It does foreclose "a map atlas plus an embedded registration form on one page" — say so if that's wanted, and the fix is per-instance auth + theme root rather than a page lock.
  • Memory mode costs three real things, all better than a blank widget but none free: the widget's route isn't in the URL (not linkable/shareable from that page), Back leaves the host page, and <Link> hrefs resolve against the host origin so a middle-click opens a host URL that probably 404s. Documented at the branch point in Widget.tsx.
  • Known follow-ups, deliberately not in scope (they need files sibling tickets own): a linkable axis on WidgetMode so ShareView/RegistrationView stop falling back to window.location.href when the widget's route isn't in it — in memory mode that hands the host's own fragment to third-party share intents, which lib/report.ts already strips for its own reporting; and tightening the Link atom's last-gate guard from href.startsWith('/') to safePath(href) (unreachable today — every href already goes through safePath — but memory mode weakens the "inert under HashRouter" reasoning the guard was documented with).
  • widget.label was added to nine of ten locales; hu is left to fall back to en because its sibling strings are still English and inventing Hungarian is worse than falling back.
  • Implementation report: .claude/reports/92-widget-mount-hardening.md.

Closes #92

🤖 Generated with Claude Code

Ardnived and others added 10 commits August 6, 2026 18:15
The embedded widget routes off the URL fragment under the `!` basename, but the
fragment belongs to the host page first. A WordPress URL carrying `#respond` is
read by react-router's hash history as a location outside the basename, so
`stripBasename` returns null and the widget renders NOTHING.

`mountRoute` makes that a three-way decision instead of the old two-way guard —
ours (a real `#!…` route wins over `base-path`), free (unclaimed, or an `#!…`
path `safePath` rejects, so ours to normalise), or foreign (the host's anchor,
never touched). Pure, so the hostile inputs are pinned in the node lane.

Refs #92

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Two mount-path defects, one guard. A host URL carrying `#respond` /
`#comment-123` rendered a BLANK widget; on a clean URL the boot write assigned
`window.location.hash`, which PUSHES a host history entry, so the visitor's
first Back press appeared to do nothing.

The widget now acts on `mountRoute`: it claims a free fragment with
`history.replaceState` (no entry, host `history.state` preserved), leaves a host
anchor completely alone and routes off-URL through a MemoryRouter instead, and
degrades to that same off-URL routing if a sandboxed document refuses the write
— where before it would have mounted a HashRouter over a fragment it never got.

Refs #92

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Two ways a host page could go wrong quietly. A second copy of the embed script
threw NotSupportedError from `customElements.define` into the host's console;
the docs name two different bundle URLs, so it is a plausible mistake. And a
second <sahaj-atlas> element silently ran on the FIRST instance's API key and
stole BrandTheme's theme root, a sharing the code only ever acknowledged in a
comment.

Both are now explicit: a repeat definition is a no-op with a note, and a second
element renders nothing and says why. The decision is a claim frozen per
instance, made above everything a widget does to the page — so a duplicate
never reaches the API key, the fragment, or the theme root.

Console text rather than an on-page notice: this is a host misconfiguration,
and injecting untranslated developer copy into somebody's public page is worse
than putting it where the integrator is already looking.

Refs #92

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The app's ResetErrorBoundary sits INSIDE Providers and BrandTheme, so a throw
from either of those — the query client, the theme engine, the i18n boot —
unmounted the whole widget with nothing on screen and nothing reported. It never
took the host page down, which is why it went unnoticed; it just left a hole in
their layout.

The new outermost boundary's fallback depends on none of the things that can be
what failed: no t(), no theme tokens, no Tailwind class a CSS-injection failure
could have taken with it, no query client. Inline spacing only, inheriting the
host's colour and font. It reports through `reportInternalError`, the single
seam a real reporter wires into.

Refs #92

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…he host head

The widget wrapper carried `dir` but no `lang`, so a French atlas on an English
host was announced with English pronunciation (WCAG 3.1.2, Language of Parts) —
and the embed was an unbounded run of content in the middle of somebody else's
page, with no landmark to jump to or out of. It now carries `lang` (reactive,
like `dir`), `role="region"` and a localized name; both attributes inherit down
the DOM tree, which display:contents does not interrupt.

The og:locale Helmet write is gated to standalone for the same reason the
canonical/og:url advertising already is: embedded, that <head> is the host's,
describing their document rather than the widget inside it.

`widget.label` is added across every locale but hu, whose sibling strings are
still English — leaving it to fall back is honest; inventing Hungarian is not.

Refs #92

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The foreign-hash fix is only observable against a page that HAS an anchor.
Strictly additive: a spacer and an `#respond` target below the widget, so
`demo.html#respond` reproduces the WordPress comment-link shape.

Refs #92

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
All four cleanup angles landed on the same two things, so both are fixed at the
layer they belong to rather than patched in place.

- The local guarded-console wrapper was a verbatim clone of
  `reportInternalError`, comment included, which quietly falsified that
  function's "single call site for a real error reporter" claim — and the two
  cases it swallowed (a doubled script, a duplicate element) are exactly what a
  reporter would most want. It is now `reportIntegrationWarning`, its sibling.
- The one-per-page rule moves from a React hook to the custom element. Counting
  ELEMENTS in a render pass meant claiming module state during render and
  releasing it in an effect — asymmetric, and a render React discards would have
  leaked the claim and locked the real widget out. In `connectedCallback` /
  `disconnectedCallback` the pair is symmetric, a refused element never mounts a
  React root at all, and the hook-count caveat disappears with the hook.

Also: the outermost boundary moves to the element's React root, where it can
also see the mount decision and the router (it stays in App.tsx too, for the
standalone entry); `useLocale` hands back the `t` it already holds instead of a
second i18next subscription on the widget's root fiber; `mountRoute` reads
`base-path` once; a dead disjunct and a duplicated rationale go.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
/code-review caught this, and it aimed the bug straight back at us: the classifier
only knew `#!/gb/london`, the shape the BOOT write produces. `Router` normalises
the basename `!` to `/!` and `joinPaths` puts a slash in front of it, so from the
first in-widget click the address bar reads `#/!/gb/london` — and reading that
back classified the widget's own deep link as the HOST's anchor. Every reload of
a page the visitor had navigated to would have dropped into memory routing and
booted at the root, with lint, typecheck and the unit lane all green.

Both spellings are ours now. The reason the pure spec couldn't catch it is that
it only ever knew what `mountRoute` decides, never whether react-router agreed —
so `hash.router.test.tsx` (the lane's second jsdom spec) pins the PAIRING in both
directions: every hash we call ours resolves to a real location under the router,
and every hash the router writes is still ours when read back. It also pins the
premise of the memory branch: `#respond` renders null.

Refs #92

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The one-per-page guard didn't work. @r2wc/core sets its own "connected" flag to
true in ITS constructor, and its attributeChangedCallback renders whenever that
flag is set — so an element carrying `api-key` (every real one) mounted a React
root during attribute upgrade, before connectedCallback could refuse it. Both
duplicates ran, and the console said the second "will not render". Probed against
@r2wc/[email protected] with a fake renderer: MOUNT, connectedCallback, UPDATE, MOUNT,
connectedCallback, REFUSED. Resetting the flag in our constructor gives
connectedCallback, MOUNT(api-key intact), connectedCallback, REFUSED.

Two more from /security-review, both on the mount write:

- `replaceState` took a bare `#!` reference, which resolves against the document
  BASE url — so a host page with `<base href="/blog/">` had its path rewritten and
  its query dropped at widget mount, and a cross-origin `<base>` threw, downgrading
  that whole site to memory routing forever. Absolutised against the current
  location instead; react-router's hash history special-cases `<base>` for the
  same reason.
- The API key is released with the page on disconnect. It's claimed under
  `if (!apiKey)`, so an element re-added with a different `api-key` kept
  authenticating as the first: the element gate stops concurrent misuse, not
  sequential.

Refs #92

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ond jsdom spec

- `tests.md`: the jsdom exception said "exactly one spec qualifies" and now names
  two — with the reason the second earns it. `hash.test.ts` covered the classifier
  exhaustively and still missed that react-router writes `#/!/x`, because a pure
  spec can only pin what OUR function decides, never whether the library it models
  agrees. Extract the pure part first is still right; it isn't sufficient where
  that part encodes a foreign contract.
- `components.md` + `CLAUDE.md`: routing is HashRouter *unless* the host's anchor
  already owns the fragment, plus the hash's two spellings and the one-element rule.
- `i18n-and-state.md`: the stack is a function of the ROUTER's location, not the
  address bar's; and `RootBoundary` above everything the other boundaries stand on.

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

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

Copy link
Copy Markdown

Deploying sahajatlas with  Cloudflare Pages  Cloudflare Pages

Latest commit: 649a376
Status: ✅  Deploy successful!
Preview URL: https://f5cdc038.sahajatlas.pages.dev
Branch Preview URL: https://fix-widget-mount-hardening.sahajatlas.pages.dev

View logs

Two conflicts, both keep-both:

- CLAUDE.md — this branch rewrote the Routing row for the two-router mount,
  main rewrote Build tool + Data in the same table. Kept all three.
- src/Widget.tsx — this branch restructured the wrapper (lang, role, the
  hash/memory branch), #113 added WIDGET_SCOPE_CLASS to its className.
  Kept the restructure and carried the scope class onto it: without that
  class the embed renders entirely unstyled.

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

Copy link
Copy Markdown

@Ardnived
Ardnived merged commit 3c03fbc into main Aug 7, 2026
5 checks passed
@Ardnived
Ardnived deleted the fix/widget-mount-hardening branch August 7, 2026 04:21
Ardnived added a commit that referenced this pull request Nov 1, 2026
…ete dead icons (#351)

* fix(event): an online class reads in the viewer's time, with the host's clock beneath

An online class took its weekday and date from the viewer's zone but its
time from the host's, so a Wednesday 19:30 Prague class read "Every
Thursday · 7:30 PM" in Sydney. The time now comes from `next` too, so
the main line is wholly the viewer's ("Every Thursday · 3:30 AM"), as
the calendar and the date filters already were.

The faded line under "Online • Hosted from Prague" now gives the host's
own clock and city through `time_in_place` ("Wed 7:30 PM in Prague"),
with the short weekday only when the host's day differs, and only when
the two wall clocks differ. It replaces the viewer-region label, so
`reconciledViewerPlace`, the IP schema's `region` and `timezone`, and
the online-event trigger of the IP lookup are gone. The lookup itself
stays: the "classes near you" prompt, the recovery offer and the share
ordering still read it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(routing): open the home region without pushing a host history entry

The first open navigated to the client record's home region (or a
path-mode `atlas` default) with a push, so a visitor's first Back press
only moved the widget back to the world list, against #112 and the
embedding guide's "mounting does not add a history entry". It now
replaces the root entry, so Back leaves the host page.

The guide's path-mode paragraph promised that Back returns to the world
list; it now says Back leaves the page, and the URL section says when
the widget writes the parameter on first open.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(routing): degrade a path embed to query routing only for a refused key

`PathBoot`'s boundary rendered `<Atlas />` with no prefix for any throw
from the client-record read, so an outage or a 5xx dropped a
`routing=path` embed to query routing: a warning blamed the record for
a missing canonical embed, and once "Try again" succeeded the widget
wrote `?atlas=` URLs under the path prefix.

The fallback now degrades only when `classifyError` calls the failure
`config` (a refused key), which keeps App's own configuration-error
screen. Anything else rethrows to the RootBoundary's reload notice.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* refactor(icons): delete the brand marks nothing renders

`Logo`, `SocialIcon` (with `ZoomIcon`, `GoogleMeetIcon`, `YoutubeIcon`)
and `BaseIcon` were imported only by their own story and test. Their
files, `Icons.test.tsx`, the story's "Brand marks" section and the
atoms barrel's `export * from './Icons'` go. The Lucide usage gallery
and `Icons.usage.test.tsx` stay.

The guides that described the folder as holding brand marks, the
exported-barrel exception list, the SSR template pointer in
docs/testing.md and two comments naming `BaseIcon` or a long-gone
`symbols.tsx` now say what is there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* refactor(loader): drop the exports the classic shim needed

`start` and the `safeLoaderPath` re-export existed for the classic
shim and its pin spec. The shim is gone and nothing imports either:
the loader spec imports the entry for its side effects, and
`literals.test.ts` reads `safeLoaderPath` from `./literals`. Both
exports and the comments describing the shim's `<head>` path go.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs(changelog): link the audit fixes to their PR

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(event): the host clock drops the city the line above it names

The faded host-clock line read "Wed 7:30 PM in Prague" directly under
"Online • Hosted from Prague". The `in %{city}` clause earned its place
while the line named the VIEWER's region, a different place from the
host's; once the clock moved to the host's own zone both lines named the
same city and the clause carried nothing. It is now the bare clock.

That unwires `event.display.time_in_place`, and this repo cannot delete a
CMS key: sydevs/SahajCloud#1057 removes it from `sy-atlas-translations`
and the ten seeds. Until that ships, the key would sit in the snapshot
referenced by nothing, which `translations.test.ts`'s dead-key direction
refuses — so that spec gains `RETIRING_KEYS`, the mirror of the
`PENDING_KEYS` registry it already had for a key published ahead of its
call site. The window is real in both directions and only one of them had
a home. Its own pin fails the entry once the sync drops the key, or once a
call site asks for it again; both halves were watched failing.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjYPMwt4U3zw69HxZTF

* refactor(event): delete the timeHint nothing reads

`EventDisplay.timeHint` had no reader outside its own spec, and its JSDoc
still called the `'viewer'` value "load-bearing" — a claim that stopped
being true when the surfaces that branched on it were replaced by reading
the display zone directly. Same dead-surface family as this branch's two
other `refactor` commits.

The three assertions on it go with it. Nothing is lost: each sat beside
the zone and weekday assertions that are the real statement, and the
Prague-viewer half, which asserted only the hint, now asserts the instant
and zone it shares with the Sydney viewer — which is what "physical
events never convert" actually means.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjYPMwt4U3zw69HxZTF

* docs(embedding): say the reload notice is untranslated English

A `routing=path` embed whose client-record read fails for any reason but
a refused key now reaches the last-rung screen. Both guides said what it
asks the visitor to do and neither said what it looks like: one line of
untranslated English, with no "Try again" control, on a non-English page
too. A host reading only the behaviour would expect the localized screen
query routing gives for the same passing 5xx, so the asymmetry is stated
rather than left to be discovered on an outage.

The CHANGELOG's online-class entry also still quoted "Wed 7:30 PM in
Prague" as the faded line.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjYPMwt4U3zw69HxZTF

* fix(routing): a path embed's read failure reaches the localized retry

A `routing=path` embed sent every client-record failure but a refused key
past `App` to `RootBoundary`, whose `RootFallback` is one line of
untranslated English with no way out but a page reload. In query mode the
same `clients/me` 5xx reaches `ErrorFallback`, localized and with "Try
again", so a path embed answered a transient blip worse than a query one
for no reason: `RootBoundary` is the rung for a failure in what the app is
BUILT on, and a classified network failure is not one.

The boot surface now renders `ErrorFallback` itself, through
`ResetErrorBoundary` rather than a bare boundary — its
`QueryErrorResetBoundary` is what makes the retry re-read the record
instead of re-throwing the rejection React Query cached, and its composed
`onError` keeps the report that the boundary's `onError` carried. The
provider moves above the boundary so the screen is inside it. A refused
key still degrades to query routing.

`ErrorFallback` gains `canReport`, a surface limit beside its existing
`canNavigate: false`: this surface mounts above `ReportIssueModal`'s host
and above the theme root it portals into, so the report action would open
nothing.

`Widget.path-boot.test.tsx` is the first spec over this boundary. Each of
its four cases was watched failing against the defect it names — the
rethrow, a bare `ErrorBoundary` (the read ran once, not twice), the report
action left on, and a degrade arm that no longer matches a refused key.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjV2heZgC6TooMov6pV

* docs(embedding): the path-mode outage screen is the localized one

The guides and the changelog entry both described the last-rung reload
notice, which a `routing=path` embed no longer reaches for a failure that
is not a refused key. Both now say what a visitor gets instead — the
widget's own error screen with a retry, the same one query mode shows —
and both state the two limits a host would otherwise discover on an
outage: the copy falls back to English if the outage took the
translations too, and the screen offers no report control, because the
report form mounts below the point where path mode waits.

`docs/rules/i18n-and-state.md`'s boundary section said `ErrorFallback`
renders only inside `App`.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjV2heZgC6TooMov6pV

---------

Co-authored-by: Claude Opus 5.5 <[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.

fix(widget): survive foreign hashes and harden the mount path

1 participant