Skip to content

fix: route widget through widget.osc.earth/osa, not workers.dev - #438

Merged
neuromechanist merged 13 commits into
developfrom
feature/issue-437-widget-custom-domain
Sep 22, 2026
Merged

neuromechanist merged 13 commits into
developfrom
feature/issue-437-widget-custom-domain

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #437. The chat widget called the Cloudflare Worker by its account-scoped *.workers.dev hostname. That hostname is pinned in nemarOrg/website's production Content-Security-Policy (that repo's ADR 0017), so moving the worker to a different account would force a coordinated cross-repo release.

Route through a stable, product-owned osc.earth host instead. The worker keeps sitting in front of api.osc.earth (the FastAPI backend) as the security proxy (Turnstile, rate limiting, CORS, backend API key injection); the widget still never calls the backend directly.

Name: widget.osc.earth/osa / develop-widget.osc.earth/osa (maintainer decision, superseding this PR's earlier assistant.osc.earth)

widget.osc.earth is a generic host reserved for widgets in general; /osa is this widget's own path under it, so a future widget can be added at its own path on the same host later instead of consuming a subdomain each. osa.osc.earth (referenced in src/api/routers/widget_test.py) stays as-is; it names where the widget's static JS file is hosted, a different concern from where the API it calls lives.

This is a path-mounted route, not a whole-hostname Custom Domain

A Cloudflare route of the form widget.osc.earth/osa/* delivers the full path to the worker, prefix included -- it sees /osa/hed/chat, not /hed/chat. Every matcher in workers/osa-worker/index.js is anchored and counts path segments, so an unhandled prefix makes every one of them miss; the request falls through to the router's own 404, silently, with nothing logged.

Fixed with stripMountPrefix(), applied once at the top of fetch() before any route is matched, rather than baking /osa into each route's own regex (which rots the first time someone adds a route). The worker still matches every route unprefixed, so the two *.workers.dev hostnames and wrangler dev keep working exactly as before.

wrangler.toml now uses an ordinary [[routes]] zone route (pattern = "widget.osc.earth/osa/*", zone_name = "osc.earth") instead of custom_domain = true. A Custom Domain maps one whole hostname 1:1 to one worker and cannot carry a path -- that would rule out ever mounting a second widget under widget.osc.earth at its own path.

Also fixed, found only by deploying: once a [[routes]] table is present, wrangler deploy defaults workers_dev to false unless told otherwise -- shipping this as originally configured would have silently taken down the existing osa-worker-dev.<account>.workers.dev hostname (confirmed: it 404'd/errored after the first dev deploy in this session). workers_dev = true is now explicit in both the top-level and [env.dev] tables; redeploying dev restored it.

Tests

workers/osa-worker/test-routing.js (new) drives the real exported fetch(request, env, ctx) with a real Request and a stub env (no BACKEND_URL/rate-limit bindings/Turnstile secret, so every proxied route fails closed at 503 rather than making a network call -- which is exactly what lets these tests observe routing, distinct from backend behavior). 55 assertions: every route this worker defines, unprefixed and under /osa, asserted to reach the same non-404 status both ways; reserved-path and invalid-community-id rejection under the prefix; and a /osafoo/chat case proving the prefix strip requires an exact /osa segment, not a string-prefix match.

Note: this branch's index.js has no /:communityId/chat/resume route (it exists only on the still-unmerged feature/issue-429-epic-browser-execution branch) -- not tested here, since there is no such route in this file to exercise. Everything this file does define is covered.

Wired into .github/workflows/tests.yml and test.yml alongside a node --check step for index.js.

Mutation proofs

  • Commented out stripMountPrefix's body (identity passthrough) and reran test-routing.js: 27 of 55 assertions failed, all with the prefixed path returning 404 where the unprefixed one returned 503 (e.g. /osa/hed/chat status matches unprefixed /hed/chat expected 503, got 404). Restored; back to 55/55.
  • Reverted the widget's two endpoint literals to the old osa-worker(-dev).shirazi-10f.workers.dev names and reran frontend/test-endpoint-resolution.js: 12 of 13 assertions failed (wrong endpoint per hostname class, workers.dev string present, literal widget.osc.earth missing). Restored; back to 13/13.

Dev provisioning: done and verified; production not touched

Deployed with bunx cfman wrangler --account neuromechanist deploy --env dev from workers/osa-worker (this account holds 10f166f3ec8395ff4a219f581c5f359d, the account already named in wrangler.toml, and has zone access to osc.earth). Wrangler reported the route attached: develop-widget.osc.earth/osa/* (zone name: osc.earth).

Gap found by verifying, not by trusting the deploy report: a plain zone route does not provision a DNS record (unlike custom_domain = true, which does). develop-widget.osc.earth has no DNS record at all yet, so:

$ curl https://develop-widget.osc.earth/osa/health
curl: (6) Could not resolve host: develop-widget.osc.earth

Forcing resolution to the zone's own edge IP confirms the worker-side configuration is correct and live (the wildcard *.osc.earth cert covers the new host, and the route dispatches correctly) -- this just proves the gap is DNS-only, not a code or route-config problem:

$ curl --resolve develop-widget.osc.earth:443:104.21.18.166 https://develop-widget.osc.earth/osa/health
{"status":"healthy","proxy":"operational","environment":"development","backend":{"status":"healthy", ...}}

$ curl --resolve develop-widget.osc.earth:443:104.21.18.166 https://develop-widget.osc.earth/osa/communities
HTTP 200

$ curl --resolve develop-widget.osc.earth:443:104.21.18.166 https://develop-widget.osc.earth/osa/hed/
HTTP 200

$ curl -X POST --resolve develop-widget.osc.earth:443:104.21.18.166 https://develop-widget.osc.earth/osa/hed/chat -d '{}'
HTTP 422   # reached the real dev backend, which rejected the empty test body -- not a 404

DNS is now provisioned, and dev is verified over real public DNS

Both records were created on 2026-09-21 in the osc.earth zone, additively. Nothing existing was modified or deleted:

Name Type Content Proxied
develop-widget.osc.earth AAAA 100:: yes
widget.osc.earth AAAA 100:: yes

100:: is the IPv6 discard prefix, which is Cloudflare's documented target for a hostname that exists only to carry a Worker route and has no real origin. The record makes the name resolve to the Cloudflare edge; the route decides what answers.

Dev now verifies without --resolve:

https://develop-widget.osc.earth/osa/health        200   (dev backend 0.8.13.dev1)
https://develop-widget.osc.earth/osa/communities   200
https://develop-widget.osc.earth/health            530   correctly unrouted, no /osa prefix

demo.osc.earth, develop-demo.osc.earth, api.osc.earth and both osa-worker*.workers.dev hostnames were re-verified after the dev deploy and the DNS change. All 200.

https://widget.osc.earth/osa/health currently returns 522, which is the expected intermediate state: the name resolves to the edge, no production route is attached yet, so the edge tries the 100:: origin and that discards. It starts answering when production deploys.

Production deploys through CI, not by hand

Correcting an earlier version of this section, which proposed a manual wrangler deploy. .github/workflows/sync-worker-cors.yml already owns worker deployment:

  • push to develop touching workers/osa-worker/** runs wrangler deploy --env=dev
  • push to main runs wrangler deploy

So the production route attaches when develop reaches main through the normal release, and no manual deploy should be run. A hand-run wrangler deploy would push a local worktree straight to production, outside that flow.

Verify after the production deploy with curl https://widget.osc.earth/osa/health and curl https://widget.osc.earth/osa/communities. Do not use /osa/version: the worker proxies /version to the backend, the backend defines no such endpoint, and it returns 404 on every host including osa-worker*.workers.dev today. Pre-existing and unrelated to this PR.

Zone access for the deploy is confirmed

Registering a [[routes]] entry needs permission on the zone the route lives in, not just on the worker, so a token that deployed this worker fine for months can start failing the moment a route appears in wrangler.toml. That reads as a pipeline outage rather than a widget bug, which is why it is called out.

Not a concern on this zone. secrets.CLOUDFLARE_API_TOKEN, which the sync-cors job deploys with, already provisions custom domains on osc.earth for the status and branch deployments, so its zone access predates this route by a long way. The dev rollout used the neuromechanist account token, which has it too. Nothing outstanding; recorded in wrangler.toml for whoever next adds a route on a zone the deploying identity does not already own.

Cross-repo coupling (flagging, not fixing here)

nemarOrg/website PR #342 carries nemar.org's production Content-Security-Policy, recorded there as ADR 0017.

Handled. nemarOrg/website commit 4747033 adds https://widget.osc.earth and https://develop-widget.osc.earth to connect-src alongside the two *.workers.dev names rather than replacing them, so the two pull requests are safe to land in either order. Listing both is not tidiness: embedders pin SRI-hashed widget builds that persist indefinitely and keep calling the old hostnames, so dropping those entries the moment this route is live would break chat on pages neither repository controls. They come out in a follow-up once production is live and cached builds have turned over.

Gates

  • bun workers/osa-worker/test-routing.js -- 55/55
  • bun frontend/test-streaming.js -- 69/69
  • bun frontend/test-citation-markers.js -- 10/10
  • bun frontend/test-endpoint-resolution.js -- 13/13
  • node --check workers/osa-worker/index.js / node --check frontend/osa-chat-widget.js -- pass
  • uv run ruff check . / uv run ruff format --check . -- pass
  • uv run pytest tests/ -m "not integration and not llm and not network" -q -- 2281 passed, 14 skipped, 1 known pre-existing failure (test_version_shows_version, issue test_version_shows_version fails locally and passes in CI, because rich colorizes on a TTY #434, TTY-dependent, green in CI), same as develop

The widget hardcoded the worker's account-scoped *.workers.dev hostname
as its API endpoint. That name is now pinned in nemarOrg/website's
production CSP (#437), so moving the edge to a different Cloudflare
account would require a coordinated cross-repo release.

Point the widget at a stable, product-owned custom domain instead:
assistant.osc.earth (production) and develop-assistant.osc.earth (dev),
single-level subdomains matching the existing demo.osc.earth /
develop-demo.osc.earth convention (avoids SSL cert issues on a
double-level subdomain). The worker keeps sitting in front of the
FastAPI backend as the security proxy; the widget never calls
api.osc.earth directly.

frontend/index.html duplicated the hostname-to-environment detection
and the endpoint literals. It now reads
OSAChatWidget.getConfig().apiEndpoint instead, so the resolution logic
lives in exactly one place (osa-chat-widget.js), as #437 asked.
Declares [[routes]] / [[env.dev.routes]] with custom_domain = true for
assistant.osc.earth and develop-assistant.osc.earth, resolved against
the osc.earth zone (already fully on Cloudflare). Documents the exact
wrangler deploy commands that register the Custom Domain plus DNS
record, since the account this session runs under cannot provision
the zone directly.

Updates the security architecture diagram and the worker README to
describe the actual public hostnames rather than only the generic
*.workers.dev placeholder used in the self-hosting examples.
New hand-rolled bun test script, following the frontend/test-streaming.js
precedent (no test framework added). Loads the real widget source in a
vm context for each hostname class the widget detects and asserts the
resolved apiEndpoint, and asserts no 'workers.dev' or account-subdomain
string survives in the widget source.

Wired into both .github/workflows/tests.yml and test.yml alongside the
existing frontend-tests step.

Verified this test fails (all 12 assertions) when the endpoint literals
are reverted to the old shirazi-10f.workers.dev hostnames, and passes
again once restored.
@github-actions

github-actions Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Preview Deployment

Name Link
Preview URL https://feature-issue-437-widget-cus-demo.osc.earth
Branch feature/issue-437-widget-custom-domain
Commit ffa0fe0

This preview will be updated automatically when you push new commits.

widget.osc.earth/osa is a path-mounted Cloudflare route, so the full
path (prefix included) reaches the worker -- every anchored route
matcher would otherwise miss and fall through to the 404 default.
stripMountPrefix() removes a leading "/osa" once, before any route is
matched, and the worker still matches unprefixed paths unchanged so
the existing *.workers.dev hostnames and `wrangler dev` keep working.

Adds test-routing.js, driving the real exported fetch() with a real
Request and a stub env, and wires it into both CI workflows alongside
a syntax check for index.js.
Closes #437. assistant.osc.earth / develop-assistant.osc.earth are
replaced with widget.osc.earth/osa / develop-widget.osc.earth/osa, the
maintainer's chosen name: widget.osc.earth is a generic host reserved
for widgets in general, and /osa is this widget's own path under it,
so a future widget can be added at its own path without consuming a
subdomain of its own.

Updates test-endpoint-resolution.js's expected endpoints and adds an
explicit assertion that the retired assistant.osc.earth name is gone
from the widget source.
widget.osc.earth/osa/* is a path mount, so custom_domain = true is
wrong: a Custom Domain maps one whole hostname 1:1 to one worker and
cannot carry a path, which would rule out ever adding a second widget
under the same host. Switches to an ordinary [[routes]] zone route
with a path pattern for both environments.

Also sets workers_dev = true explicitly in both the top-level and
[env.dev] tables: once a [[routes]] table is present, wrangler
defaults workers_dev to false on deploy unless told otherwise, which
would have silently dropped the existing osa-worker*.workers.dev
hostname the moment this shipped (caught during dev deploy; see PR).

Documents that, unlike a Custom Domain, a plain route does not
provision a DNS record -- confirmed during the dev rollout, where the
route was live on the worker side (verified by forcing resolution to
the zone's edge) before any public DNS record existed for the host.
@github-actions

Copy link
Copy Markdown
Contributor

⚠️ Worker Deployment Required

Worker changes detected. After merging to main or develop, the workflow will automatically deploy the worker.

Manual deployment (if needed):

cd workers/osa-worker
wrangler deploy --env dev  # for develop branch
wrangler deploy            # for main branch

@neuromechanist neuromechanist changed the title fix: route widget through assistant.osc.earth, not workers.dev fix: route widget through widget.osc.earth/osa, not workers.dev Sep 22, 2026
neuromechanist added a commit to nemarOrg/website that referenced this pull request Sep 22, 2026
The OSA widget moves to widget.osc.earth/osa and
develop-widget.osc.earth/osa (OpenScience-Collective/osa#438, closing
#437). Add both origins to connect-src alongside the existing
workers.dev names rather than replacing them: embedders pin SRI-hashed
widget builds that persist indefinitely and still call the old
hostnames, so listing both keeps this policy safe to promote before or
after the new route goes live.

connect-src matches by origin and ignores the path, so the /osa mount
point does not appear in the policy; a test asserts it does not.

Strengthen the existing site-wide assertions to check the connect-src
directive specifically instead of the whole policy string, since a host
landing in another directive would satisfy a whole-string check while
the browser still refused the fetch. Mutation-verified in both
directions: removing the new hosts fails the new test, and leaking the
API hosts into script-src fails the separation test.

Tested: bun test src/middleware.test.ts (57 pass), lint, typecheck.
DNS for widget.osc.earth and develop-widget.osc.earth now exists, so
the comment saying it is missing is stale. Replace it with what the
rollout actually established.

Two traps worth keeping: an ordinary zone route provisions no DNS and
reports success anyway, so the hostname must be curled rather than the
deploy output read; and registering a route needs permission on the zone,
which CLOUDFLARE_API_TOKEN may not have, in which case the sync-cors
deploy step fails on every merge touching this directory.

Also corrects the deploy instructions: sync-worker-cors.yml owns
deployment on push to develop and main, so the manual wrangler commands
this comment previously recommended would bypass the release flow.
The route-registration permission trap is real and worth recording, but
it is satisfied here: both the neuromechanist account token used for the
dev rollout and CLOUDFLARE_API_TOKEN used by sync-cors have zone access.
Keep the trap, drop the open question.
It already provisions custom domains on that zone for the status and
branch deployments, so the permission predates this route. A reason is
checkable; a bare assertion is not.
stripMountPrefix stripped a leading /osa from every request regardless of
which host it arrived on. The bare workers.dev hostname stays live
(workers_dev = true) and Cloudflare adds no prefix there, so a path-only
strip ate a real leading segment.

A community whose id is "osa" is valid today: isValidCommunityId accepts
it and RESERVED_PATHS does not list it. The product is named OSA, so it
is a plausible id for someone to create. Every symptom of the collision
looked like an unrelated bug: /osa/ answered the API root instead of the
community, /osa/chat 404ed, and /osa/logo was re-read as community
"logo" and failed on a missing backend, which in production reads as an
outage. Two independent reviewers reproduced it, one against a local
echo backend showing the wrong community reaching the upstream.

Stripping is now gated on MOUNTED_HOSTS, the hosts wrangler.toml actually
mounts the worker on. Adding a mount host without listing it there fails
loudly instead of silently: every route 404s, and the fall-through now
logs raw path, stripped path and host, so drift between MOUNT_PREFIX and
the deployed route is greppable in wrangler tail rather than invisible.

Tests go from 55 to 93. New coverage: the unmounted host does not strip,
query strings survive on the route that forwards them, the admin metrics
routes (previously untested entirely), and the path actually forwarded to
the backend rather than only the status code. That last one uses a real
Bun.serve standing in at the HTTP boundary, so the worker's own routing,
stripping and fetch all run for real.

Mutation-verified: removing the host gate fails 19 of 93; disabling the
strip fails 27; forwarding the raw path instead of the stripped one fails
exactly the one assertion that watches it.
index.html read window.OSAChatWidget.getConfig() at the top level of its
script block. If osa-chat-widget.js failed to load for any reason (CDN
trouble, an ad blocker, a CSP refusal, or a route live while DNS is not,
all of which this branch's own rollout produced), that threw uncaught,
and every later top-level statement including the loadCommunities() call
never ran. The page rendered an empty div instead of the "Could not load
communities" box it already builds.

That was a regression this branch introduced: before it, index.html
derived the endpoint itself and never depended on the widget loading.

Resolution now happens inside loadCommunities()'s try, so the failure
routes into the same error UI as any other backend failure. The
deduplication itself is kept; only the hard dependency is removed.
test.yml's all-tests job listed frontend-tests in needs but never checked
its result, so a red frontend job still reported "All Tests Passed".
tests.yml already checks it correctly.

That job is where the worker routing tests live, and test.yml is the
workflow that runs on a develop to main release PR, so the gap was worst
exactly where it mattered most.
The [env.dev] comment said workers_dev is not inherited from the top
level. That is Wrangler 1 behavior. Wrangler 4 marks the field
inheritable, and reading this config back through wrangler's own
unstable_readConfig with the line deleted still reports workers_dev true
for that environment. The line stays as deliberate redundancy, since the
value flips to false on its own once routes are present, but the stated
reason is now true rather than confidently wrong.

Also from review:

- wrangler.toml told the reader never to run a manual deploy while the
  same workflow's PR bot comment hands them the commands. Both are right
  for different situations; the caveat the bot has no room for is now
  stated here.
- Spelled out Content-Security-Policy and Architecture Decision Record
  before abbreviating them.
- security-architecture.md called the workers.dev names "retained but not
  public". They answer an unauthenticated 200 today; they are no longer
  advertised, which is a different claim. Box width preserved.
- The widget and its test still called the new names a "custom domain",
  which is the one thing this branch deliberately did not use.
- Replaced the ASCII em-dash substitute throughout the new prose.
- The top-level workers_dev comment said the route was "above" it.

Tested: 93 routing, 13 endpoint, 69 streaming, 10 citation, both syntax
checks, ruff check and format, 2282 pytest passed.
@neuromechanist
neuromechanist merged commit c967628 into develop Sep 22, 2026
10 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-437-widget-custom-domain branch September 22, 2026 04:28
neuromechanist added a commit that referenced this pull request Sep 22, 2026
The Trap 2 note in wrangler.toml said zone access was not a concern here,
reasoning that CLOUDFLARE_API_TOKEN already provisions custom domains on
osc.earth. That reasoning does not transfer: Pages custom domains, zone
DNS and Zone:Workers Routes:Edit are three separate grants, and the token
holds the first two but not the third.

The first sync-cors run after #438 merged proved it. Records what
actually happened, including that the script upload still succeeds so the
code goes live, and that pre-registering a route by hand does not make
the job pass, since wrangler fails reconciling a route that already
matches.

Documentation only. The permission gap itself is tracked as #439.
neuromechanist added a commit that referenced this pull request Sep 22, 2026
Addresses every finding from the two release reviews of #442.

Pins the deploy wrangler to an exact version and runs it through bun: a
floating global install could re-flip workers_dev to false, which already
took the workers.dev hostname down once during #437 with clean output.

Adds a test enforcing that MOUNTED_HOSTS and the [[routes]] patterns
agree. One drift direction is completely silent: a host in the set with
no route means Cloudflare never invokes the worker, so no log can catch
it. Mutation-verified both ways.

Enables Workers Logs, without which the 404 fall-through log added in
#438 was visible only during a live wrangler tail and could not explain
an outage after the fact.

Adds a 15-minute probe of both mounted hosts, the legacy workers.dev
name, and the host gate itself. Nothing watched these; the status
dashboard bypasses the worker entirely and stays green through a route
outage.

Repairs release.yml, dead since February 2026 because tag-release.yml
pushes tags under the default GITHUB_TOKEN, which starts no workflow
runs. Published notes have been missing the widget SRI section since.

Documents what a release cannot roll back: the tag and the PyPI upload
are immediate and permanent.
neuromechanist added a commit that referenced this pull request Sep 22, 2026
Brings the widget-hostname work (#437, #438, #440, #441) and the release
hardening (#443) onto the epic branch. Two conflicts, both real rather
than textual.

workers/osa-worker/index.js: phase 1 matched its routes against the raw
url.pathname, which predates develop's host-gated stripMountPrefix. Left
as merged, every phase 1 route would have 404'd on widget.osc.earth
while ordinary chat worked, so the two-run continuation would have been
broken on the mounted host only. Both communityAction and
communityChatResume now match the stripped pathname; the named
ROUTE_PATTERNS constants from phase 1 are kept.

workers/osa-worker/test-routing.js: both branches created this file
independently. Develop's version drives the real exported fetch handler,
phase 1's asserted against the regex constants in isolation. Kept
develop's, because a test that matches a pattern by hand cannot catch a
route wired to the wrong variable, which is exactly the bug above. Phase
1's resume coverage is re-added in that style, driving the real handler
prefixed and unprefixed.

The workflow conflicts were duplicate steps; develop already runs the
routing test in the same job.

Tested: 102 routing, 10 mounted-hosts, 13 endpoint, ruff clean, 2483
pytest passed. Note that a fresh worktree resolves Python 3.14, where
langfuse's pydantic.v1 usage fails at collection; pin 3.12 to match CI.
neuromechanist added a commit that referenced this pull request Sep 30, 2026
The file had sections for 0.8.10, 0.8.12, 0.8.14 and 0.8.15 only. The
three missing releases are written from the pull requests between their
tags (0.8.13: #438, #440, #441, #443; 0.8.11: #418; 0.8.9: #351 to #355
and #359 and #367), so the last seven releases are now all present.

Tested: docs only; each entry checked against its pull request's body.
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