Skip to content

refactor(ui): gate every anchor href through one predicate - #136

Merged
Ardnived merged 5 commits into
mainfrom
refactor/safe-href-predicate
Aug 8, 2026
Merged

Ardnived merged 5 commits into
mainfrom
refactor/safe-href-predicate

Conversation

@Ardnived

@Ardnived Ardnived commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

Summary

Lifts one href-safety predicate — isSafeHref (src/lib/shape/href.ts) — and routes all three of the app's JSX anchors through it: the Link atom, the Button atom's href form, and ActionRow's ActionCircle. ALLOWED_SCHEME now has exactly one definition.

This is defense-in-depth. No live hole is known, and none was found. Every href reaching the two previously-ungated anchors is safe by provenance today. What justifies the change is the recurrence rate, not a bug: the Link atom's own guard was lost and restored twice, and #100 found //evil.com passing an href.startsWith('/') check that read as correct. A predicate in one place with one test file is what stops the third recurrence.

Closes #114.

What each call site actually passes

Enumerated before changing anything — every production href at the two newly-gated anchors is an allowed scheme; not one is site-relative, so the gate cannot regress a working link.

Anchor Caller href
Button href form AddToCalendar.tsx:89 Google / Outlook-live / Outlook-office / Yahoo — literal https:// built in lib/ics.ts
Button href form ReportIssueForm.tsx:199 `mailto:${CONTACT_EMAIL}`
Button href form EventRegister.tsx:101 externalRegistrationUrl — SafeUrlSchema, so ^https?:
ActionCircle EventActions.tsx:104 directionsUrl(event.address) → literal https://www.google.com/maps/…
ActionCircle EventActions.tsx:117 event.website — SafeUrlSchema (/^https?:/i, .catch(null))
ActionCircle EventActions.tsx:133 `tel:${event.contactPhone}`

The .ics download is not affected: it builds a blob: URL on a detached synthetic anchor (downloadIcs), never through the Button atom — so blob: staying out of the allowed set costs it nothing.

Design notes

  • Reuses safePath, doesn't reimplement it. //evil.com, /\evil.com and the TAB/LF/CR variants (which the WHATWG parser strips before parsing, so all three read as //evil.com) stay rejected by the repo's single definition. path.test.ts is untouched.
  • Link's behaviour is unchanged — the refusal branch, the report and the <span> fallback are as they were, the href still decides alone before isExternal/target="_blank" are read, and Link.test.tsx passes unchanged, as the ticket required.
  • One failure mode, not three: report, then degrade to the same content on a non-interactive <span>. ActionCircle deliberately does not fall through to its <button> arm — that would leave a focusable control that does nothing.
  • hasAllowedScheme ships alongside as the rendering question (plain <a> vs. client-routed) that Link needs; it is not a safety gate, and a test pins that substituting it would refuse every internal route.

The inventory is asserted, not described

href.test.ts walks src/**/*.tsx with the TypeScript AST, collects every file rendering a JSX anchor, and fails unless the set is exactly those three and each imports and calls the gate. The ticket's acceptance criteria described this as a manual grep; a grep nobody re-runs is how the first three recurrences happened. Verified it bites by adding a probe component — including a probe crafted to defeat the regex-based version this replaced (an unpaired /* in a string swallows text up to the next docblock and hides a real anchor).

Stated blind spots, in the failure message: JSX only, so React.createElement('a', …) and an element-type variable don't trip it, and .ts files aren't scanned.

Review findings fixed

A /code-review pass and a /security-review pass both ran (the latter isn't required by the path grep, but this change is a security control). Neither found a bypass — the security review reports ~450k fuzzed candidates plus an exhaustive sweep of every code point at index 1, with zero origin leaks and zero executable schemes. Fixed from their findings:

  • A refused href went unreported for offline viewers. All three sites threw a bare Error; classifyError's last resort is navigator.onLine, so an offline viewer's refusal classified as offline — a kind REPORTED_KINDS withholds from the reporter. Now atlasError('unknown', …), which is the repo's stated rule anyway.
  • The inventory test's regex comment-stripping had a false pass → replaced with the AST walk above.
  • Docblock corrections: the gate judges the scheme, not the payload concatenated after it (tel:${contactPhone}); and site-relative is safe at all three anchors but only routable at Link. Button's refusal span also drops aria-label/id/onClick, which a comment had waved past as meaningless.

Deliberately not fixed (out of this ticket's scope, worth a follow-up): ActionCircle spreads ...rest after rel/target without destructuring them, so a runtime spread could set target="_blank" with no rel — unlike Link and Button, which both destructure. It is type-blocked today (React.HTMLAttributes declares neither) and no caller does it, and closing it is a behaviour change rather than this refactor.

Verification

lint + typecheck + test:run (888 tests) green; the full gate including pnpm build and the pnpm size budget was run locally and passes (381.1 / 382.8 KiB against a 395 KiB budget — the two new imports add nothing, since every module the @/lib/shape barrel re-exports was already in the eager graph).

Browser verification was not authorized this wave and isn't needed: no rendered output changes for any href the app actually passes.

Ardnived and others added 5 commits August 7, 2026 19:29
Lift `isSafeHref` into `src/lib/shape/href.ts` — safePath-clean OR an allowed
scheme — and route all three of the app's anchors through it. The `Link` atom
already decided this correctly; the `Button` atom's href form and ActionCircle
rendered their own `<a>` and never reached that code.

Defense-in-depth: no live hole is known. Every href reaching those two is safe
by provenance today, which is not a property the next caller inherits.

`ALLOWED_SCHEME` now has exactly one definition. `Link`'s behaviour is
unchanged: the refusal branch, the report and the `<span>` fallback all stay,
and the href still decides alone, before `isExternal`/`target` are read.

Closes #114

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`href.test.ts` pins the cases that justify reusing `safePath` — `//evil.com`,
`/\evil.com` and the TAB/LF/CR variants the WHATWG parser rewrites into the
first — alongside the allowed schemes, `HTTPS:` casing, and a non-string
returning false rather than throwing.

Each anchor spec also pins the hrefs its real callers pass, so a stricter
predicate would fail here rather than silently break a phone link.

Also correct the now-stale prose in `.claude/rules/data-layer.md`, which said
the other two anchors were not covered.

Closes #114

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- `isSafeHref` now calls `hasAllowedScheme` instead of re-spelling its regex
  test, so the two share the scheme list by construction rather than by copy.
- Inline Link's single-use `hasScheme` local, dropping a second name for one
  concept in one file.
- Keep the predicate's case table in `href.test.ts` only. The component specs
  had each re-enumerated an arbitrary subset of it, which is the four-copy
  drift this ticket exists to stop; they now prove wiring plus the hrefs their
  real callers pass.
- Trim the rationale that had been written out three to five times, leaving
  each site its own fact and one pointer to the predicate.

Also assert the anchor inventory rather than describing it: `href.test.ts`
walks `src/**/*.tsx` and fails if a fourth JSX anchor appears or one of the
three stops calling the gate. Verified it bites by adding a probe component.

Corrects two overclaims in prose from the previous commit — `lexicalToHtml`
also emits `<a href>`, as an HTML string sanitized by DOMPurify, so
"every href" and "three anchors" needed qualifying to JSX anchors.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Findings from /code-review and /security-review.

All three refusal sites threw a bare `Error`, which `classifyError` guesses at
— and its last resort is `navigator.onLine`, so an offline viewer's refused
href was classified `offline`, a kind `REPORTED_KINDS` withholds from the
reporter. A refused href has nothing to do with connectivity. `atlasError`
pins the kind, which is the repo's stated rule anyway.

The anchor-inventory test now parses with the TypeScript AST instead of
stripping comments by regex. The regex form had a false pass — an unpaired
`/*` in a string or line comment swallows text up to the next docblock, hiding
an anchor from the one test whose job is to find it. Verified against a probe
built to exploit exactly that. Also fixes a leading slash on top-level paths,
asserts the import rather than the bare name, and documents the blind spots
(createElement, element-type variables, `.ts` files).

Two docblock corrections: the gate judges the SCHEME, not the payload
concatenated after it; and site-relative is safe at all three anchors but only
routable at `Link`. Button's refusal span drops `aria-label`/`id`/`onClick`
too, which the comment had waved past as meaningless.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The href rule lives in data-layer.md, which is path-scoped to src/config/api
and src/types — so it never loads for the person most likely to add a fourth
anchor. components.md does load there.

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

Copy link
Copy Markdown

@cloudflare-workers-and-pages

Copy link
Copy Markdown

Deploying sahajatlas with  Cloudflare Pages  Cloudflare Pages

Latest commit: db64150
Status: ✅  Deploy successful!
Preview URL: https://9260ebb2.sahajatlas.pages.dev
Branch Preview URL: https://refactor-safe-href-predicate.sahajatlas.pages.dev

View logs

@Ardnived
Ardnived merged commit 31e61bf into main Aug 8, 2026
5 checks passed
@Ardnived
Ardnived deleted the refactor/safe-href-predicate branch August 8, 2026 03:35
Ardnived added a commit that referenced this pull request Aug 8, 2026
One conflict, in .claude/rules/tests.md: this branch and #101 each added a
fourth jsdom spec to the same list, and both bumped its count to "Three".
Kept both entries, corrected the count to Four, and fixed #101's "least
optional of the three" to match. The ordinal in the report-form entry
still reads correctly — with sanitize.test.ts second, it is the third
cautionary tale.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Ardnived added a commit that referenced this pull request Aug 11, 2026
* chore(claude): widen the security-review trigger paths

The path grep in /finalize-pr did not match #100's branch — the one whose
entire point was hardening the Link atom's href guard. A security review ran
anyway, on judgement, and that is the only reason the protocol-relative-URL
gap (//evil.com walking through href.startsWith('/')) was caught before merge.
A gate that depends on someone overriding it is not a gate.

Adds the client-side surfaces that have since become security-relevant:
the same-origin/scheme guard (shape/path.ts, shape/href.ts, atoms/Link/),
the host-page CSS isolation that #91/#104 built (styles/globals.css,
lib/scope.ts, the PostCSS scoping script + config), the app root, the
privacy opt-outs and the reporting seam Sentry hangs off, and the lockfile
for a transitive bump that never touches package.json.

Deliberately, not maximally: over the last 82 commits on main the widened
list fires 54 times against the old 51, and two of those three additions are
#111 and #136 — the href-guard branches this exists to catch. Verified to
still not fire on a locale-only or stories-only diff.

Closes #117

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

* docs(claude): re-sync the lean-gate row from SahajCloud

Pre-existing drift, found while checking this ticket's byte-identical
criterion: SahajCloud's #607 (3be34cc0, 2026-07-31) corrected its own cell
of the "Lean gate contents" row to `lint + typecheck + typecheck:tests +
test:unit` and did not port that edit to the other two copies, so all three
have disagreed on line 79 since. Adopting SahajCloud's text here — it is
strictly the accurate one — leaves ONE patch to carry to each sibling and
lets all three converge.

Refs #117

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

* fix(claude): close the gaps /code-review found in the widened list

Three findings, all accepted. Cost: ONE extra firing across the last 84
commits (54 → 55), measured before accepting.

- Unanchor the five module entries so a SPEC travels with its module.
  The `\.ts` suffixes excluded href.test.ts, path.test.ts, privacy.test.ts
  and the two report specs — so deleting an assertion triggered nothing,
  which hollowed out the very paragraph telling readers to prefer an
  assertion over a path. The pre-existing entries (src/config/api/,
  src/types/event, shape/lexical, EventDetails/) already behaved this way;
  the new ones were the inconsistent ones.
- Add src/lib/shape/hash — .claude/agents/security-reviewer.md names it
  beside Widget.tsx as the host trust boundary, "an untrusted input picking
  a branch, so audit both" (#92). Widget.tsx was listed and hash.ts was not:
  the same asymmetry as lexical-vs-path that this ticket exists to fix.
- Broaden to src/styles/ (vaul.css is the other half of the injected sheet)
  and add patches/ — a patch is arbitrary code applied to a dependency, and
  patches/[email protected] exists precisely because vaul leaked a bare
  @Keyframes into host pages.

Also rewrites the "what does not belong here" paragraph, which cited
href.test.ts as an example of an excluded surface while href.ts sat in the
list two lines above. It now names the genuinely-absent i18n-options.ts and
explains the unanchoring rule instead.

The deltas-table cell follows the list, so the sibling ports were refreshed.

Refs #117

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.

refactor(ui): gate every anchor href through one predicate

1 participant