Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(core): apply one blocked-scheme rule to all navigation paths (#5524)

Baraa Hamodi54be197d0540
diff --git a/.changeset/core-imperative-href-rule.md b/.changeset/core-imperative-href-rule.md
new file mode 100644
index 0000000000..c54211902c
--- /dev/null
+++ b/.changeset/core-imperative-href-rule.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Apply the same narrow blocked-scheme rule to native links, custom routers, clickable surfaces, and Markdown links. Rejected destinations stay visible without navigating or invoking a router, including structured URLs with a separate protocol. Ordinary URLs, safe custom schemes, downloads, and accepted router-object identity are preserved; Markdown image/resource policy is unchanged.
+
+@bhamodi
diff --git a/apps/docsite/src/__tests__/link-navigation.test.ts b/apps/docsite/src/__tests__/link-navigation.test.ts
new file mode 100644
index 0000000000..09c325e713
--- /dev/null
+++ b/apps/docsite/src/__tests__/link-navigation.test.ts
@@ -0,0 +1,66 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {createElement} from 'react';
+import {renderToStaticMarkup} from 'react-dom/server';
+import NextLink from 'next/link';
+import {describe, expect, it} from 'vitest';
+import {LinkProvider} from '../../../../packages/core/src/Link/LinkProvider';
+import {useLinkComponent} from '../../../../packages/core/src/Link/useLinkComponent';
+
+function Navigation({href, to}: {href: unknown; to?: unknown}) {
+ const Link = useLinkComponent();
+ return createElement(Link, {href, to, 'data-testid': 'destination'}, 'Go');
+}
+
+function renderNavigation(href: unknown, to?: unknown) {
+ return renderToStaticMarkup(
+ createElement(LinkProvider, {
+ component: NextLink,
+ children: createElement(Navigation, {href, to}),
+ }),
+ );
+}
+
+describe('LinkProvider with the actual Next.js Link during SSR', () => {
+ it.each([
+ 'javascript:alert(1)',
+ 'vbscript:MsgBox(1)',
+ 'data:text/html,<b>x</b>',
+ {protocol: 'javascript:', pathname: 'alert(1)'},
+ {protocol: 'javascript', pathname: 'alert(1)'},
+ {protocol: 'data:', pathname: 'text/html,<b>x</b>'},
+ {protocol: 'vbscript:', pathname: 'MsgBox(1)'},
+ ])(
+ 'renders rejected %j inertly instead of passing undefined to Next',
+ href => {
+ expect(renderNavigation(href)).toBe(
+ '<a data-testid="destination">Go</a>',
+ );
+ },
+ );
+
+ it('does not fall back to a safe href when an explicit to is rejected', () => {
+ expect(
+ renderNavigation('/safe', {
+ protocol: 'javascript:',
+ pathname: 'alert(1)',
+ }),
+ ).toBe('<a data-testid="destination">Go</a>');
+ });
+
+ it.each([
+ ['/docs', '/docs'],
+ ['#section', '#section'],
+ ['https://example.com/docs', 'https://example.com/docs'],
+ ['mailto:[email protected]', 'mailto:[email protected]'],
+ ['tel:+1234567890', 'tel:+1234567890'],
+ ['custom:document', 'custom:document'],
+ [
+ {protocol: 'https:', hostname: 'example.com', pathname: '/docs'},
+ 'https://example.com/docs',
+ ],
+ [{pathname: '/docs', query: {page: '2'}, hash: 'top'}, '/docs?page=2#top'],
+ ])('retains Next navigation for %j', (href, expected) => {
+ expect(renderNavigation(href)).toContain(`href="${expected}"`);
+ });
+});
diff --git a/apps/storybook/stories/LinkNavigation.stories.tsx b/apps/storybook/stories/LinkNavigation.stories.tsx
new file mode 100644
index 0000000000..4620e72e33
--- /dev/null
+++ b/apps/storybook/stories/LinkNavigation.stories.tsx
@@ -0,0 +1,118 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {useRef, type ComponentPropsWithRef} from 'react';
+import type {Meta, StoryObj} from '@storybook/react';
+import {Link, LinkProvider, useLinkComponent} from '@astryxdesign/core/Link';
+import {ClickableCard} from '@astryxdesign/core/ClickableCard';
+import {Citation} from '@astryxdesign/core/Citation';
+import {Markdown} from '@astryxdesign/core/Markdown';
+import {useClickableContainer} from '@astryxdesign/core/hooks';
+
+type Destination = string | {protocol?: string; pathname: string};
+
+function RouterLink({
+ href,
+ to,
+ ...props
+}: Omit<ComponentPropsWithRef<'a'>, 'href'> & {
+ href?: Destination;
+ to?: Destination;
+}) {
+ const destination = to ?? href;
+ if (destination == null) {
+ throw new Error('Router requires a destination');
+ }
+ const url =
+ typeof destination === 'string'
+ ? destination
+ : `${destination.protocol ?? ''}${destination.pathname}`;
+ return <a {...props} href={url} data-router="true" />;
+}
+
+function StructuredLink({href}: {href: string}) {
+ const Component = useLinkComponent(RouterLink);
+ const colon = href.indexOf(':');
+ const to =
+ colon === -1
+ ? {pathname: href}
+ : {protocol: href.slice(0, colon + 1), pathname: href.slice(colon + 1)};
+ return (
+ <Component to={to} data-testid="structured">
+ Structured router
+ </Component>
+ );
+}
+
+function ImperativeSurface({href, target}: {href: string; target?: string}) {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const handlers = useClickableContainer({containerRef, href, target});
+ return (
+ <div
+ ref={containerRef}
+ {...handlers}
+ role="presentation"
+ data-testid={target ? 'imperative-blank' : 'imperative'}>
+ Imperative navigation surface
+ </div>
+ );
+}
+
+function NavigationFixture({href}: {href: string}) {
+ return (
+ <div data-testid="navigation-fixture" data-destination={href}>
+ <div>
+ <Link href={href} data-testid="native">
+ Native anchor
+ </Link>
+ </div>
+ <LinkProvider component={RouterLink}>
+ <div>
+ <Link href={href} data-testid="provider">
+ Provider router
+ </Link>
+ </div>
+ <ClickableCard
+ href={href}
+ label="Delegated card surface"
+ data-testid="delegated">
+ <span>Delegated card surface</span>
+ </ClickableCard>
+ </LinkProvider>
+ <div>
+ <Link as={RouterLink} href={href} data-testid="as">
+ Per-link router
+ </Link>
+ </div>
+ <div>
+ <StructuredLink href={href} />
+ </div>
+ <div>
+ <Citation
+ source={{title: 'Citation', url: href}}
+ number={1}
+ data-testid="citation"
+ />
+ </div>
+ <div data-testid="markdown">
+ <Markdown>{`[Markdown link](${href})`}</Markdown>
+ </div>
+ <div>
+ <Link href={href} download="note.txt" data-testid="download">
+ Download
+ </Link>
+ </div>
+ <ImperativeSurface href={href} />
+ <ImperativeSurface href={href} target="_blank" />
+ </div>
+ );
+}
+
+const meta = {
+ title: 'Core/Link Navigation',
+ component: NavigationFixture,
+ args: {href: '#destination'},
+} satisfies Meta<typeof NavigationFixture>;
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+export const Destinations: Story = {};
diff --git a/docs/families/navigation-destinations.md b/docs/families/navigation-destinations.md
index 74437fe7f1..a7aa97ce37 100644
--- a/docs/families/navigation-destinations.md
+++ b/docs/families/navigation-destinations.md
@@ -12,9 +12,16 @@ owners: [cixzhang, imdreamrunner]
review_triggers: [behavior, accessibility, public-api]
verified_by:
[
+ packages/core/src/utils/safeUrl.test.ts,
packages/core/src/Markdown/parser.test.ts,
packages/core/src/Markdown/Markdown.test.tsx,
+ packages/core/src/Markdown/Markdown.renderBoundary.test.tsx,
packages/core/src/Link/useLinkComponent.test.tsx,
+ packages/core/src/Link/__tests__/Link.navigation.a11y.chromium.spec.ts,
+ packages/core/src/Citation/Citation.test.tsx,
+ packages/core/src/TopNav/TopNavMenu.test.tsx,
+ apps/docsite/src/__tests__/link-navigation.test.ts,
+ packages/core/src/hooks/useClickableContainer.test.tsx,
packages/core/src/ClickableCard/ClickableCard.test.tsx,
]
members:
@@ -96,14 +103,20 @@ must be added here even when it delegates to an existing member or shared hook.
## Shared owner
+- `spec:AST-005` owns the normalized blocked-scheme rule for every navigation
+ destination. This family owns its application across members.
- `useLinkComponent` owns destination handoff to native and custom link
- components, including the router-facing `href` and `to` seams.
+ components, including the router-facing `href` and `to` seams. Accepted
+ structured destinations retain object identity. Rejected destinations render
+ inertly without invoking the custom component.
- `useClickableContainer` owns imperative navigation from enlarged surfaces,
- including same-tab, new-tab, modifier-click, and middle-click paths.
-- Markdown owns parsing untrusted source into a destination and preserves the
- shared navigation policy at its render boundary.
-- React DOM is the supported native-anchor sanitizer. Astryx owns every path
- React does not mediate.
+ including same-tab, new-tab, modifier-click, middle-click, and delegated
+ activation. Every activation preserves the same accept/block result.
+- Markdown owns parsing untrusted source into a destination and preserving the
+ same navigation decision through rendering. Its image/resource policy remains
+ separate.
+- Native anchors follow the full shared navigation rule. React DOM's own
+ sanitization is not an exception to any blocked scheme.
## Canonical concepts
@@ -118,8 +131,8 @@ must be added here even when it delegates to an existing member or shared hook.
## Cross-component invariants
- **FR1 — Every caller-controlled navigation destination is decided before its
- sink.** No member may pass a destination to a custom router or imperative
- browser API before the shared rule runs.
+ sink.** No member may render a native navigation destination or pass one to a
+ custom router or imperative browser API before the shared rule runs.
- **FR2 — Alternate rendering keeps the rule.** Replacing a native anchor through
`LinkProvider` or `as` does not bypass destination handling.
- **FR3 — Alternate activation keeps the rule.** `_blank`, Cmd/Ctrl-click,
@@ -127,27 +140,36 @@ must be added here even when it delegates to an existing member or shared hook.
same accept/block decision.
- **FR4 — Blocked schemes cannot execute.** After browser-compatible scheme
normalization, `javascript:`, `vbscript:`, and `data:text/html` do not become
- navigation.
+ navigation, including through native anchors.
- **FR5 — Accepted destinations retain browser behavior.** Relative paths,
- fragments, protocol-relative destinations, and ordinary schemes continue to
- support native and router navigation, targets, and browser affordances.
+ fragments, protocol-relative destinations, HTTP(S), mailto, tel, and safe custom
+ schemes retain native and router navigation, targets, downloads, and browser
+ affordances. Accepted structured router destinations retain their fields and
+ object identity.
- **FR6 — Both custom-router props are sinks.** A supplied `href` and explicit
- `to` are checked independently; neither can bypass the rule through prop
- precedence or rest-prop ordering.
+ `to` are checked independently, including the scheme-bearing fields of
+ supported structured forms (`href`, `pathname`, and `protocol`) and the
+ destination they form. If either supplied destination is rejected, the result
+ is inert: the custom router is not invoked, even with `undefined`, and there is
+ no fallback to the other destination. Accepted explicit `to` values keep their
+ documented precedence when every supplied destination is accepted.
- **FR7 — Disabled and rejected are distinct.** Members keep their own disabled
semantics. Rejecting a destination prevents navigation without inventing a
disabled state, label, or visual treatment.
- **FR8 — Resource handling does not inherit navigation policy.** Images, media,
- downloads, CSS URLs, and fetch targets use their own sink-specific contracts.
- A member that handles both navigation and resources applies this family only
- to its navigation path.
+ CSS URLs, fetch targets, and downloaded content use their own sink-specific
+ contracts. An accepted link's existing download behavior is preserved. A member
+ that handles both navigation and resources applies this family only to its
+ navigation path.
## Allowed component variation
- **AV1 — Rejected presentation.** Markdown may render rejected source as text;
- a custom-link member may render without destination props; an enlarged surface
- may simply omit imperative navigation. Each member preserves its own
- non-navigation structure and accessibility contract.
+ a custom-link member renders inert content without invoking its custom router;
+ an enlarged surface may simply omit navigation. Each member preserves its own
+ non-navigation structure and accessibility contract. No component bypass prop
+ is provided; exceptional behavior belongs to caller-owned custom rendering
+ outside this contract.
- **AV2 — Native versus router navigation.** Members may use React DOM anchors,
provider-level router components, per-component `as` overrides, or imperative
browser APIs when their public contract requires that mode.
@@ -163,39 +185,41 @@ must be added here even when it delegates to an existing member or shared hook.
## Representative matrix
-| Member and state | Shared invariant | Deliberate variation |
-| --------------------------------------------------- | --------------------------------------------------------- | ------------------------------------------------------------------------- |
-| `component:Link` / native anchor | blocked destination does not execute | React DOM performs the native sink sanitization |
-| `component:Link` / custom provider or `as` | blocked `href`/`to` does not reach the router | router owns accepted client-side navigation |
-| `component:ClickableCard` / plain or modified click | every imperative or delegated exit uses the same decision | visible Card structure and nested-interactive handling remain local |
-| `component:Token` / link with remove action | surface activation and hidden link agree | remove action remains an independent sibling control |
-| `component:Markdown` / parsed link | blocked source does not become navigation | rejected source may render as text; resource policy remains separate |
-| navigation aggregate / member item | item destination uses the shared owner | tree, tab, breadcrumb, side-nav, top-nav, and menu semantics remain local |
-| `component:Citation` / linked source | blocked URL does not execute | native-anchor path and citation presentation remain local |
+| Member and state | Shared invariant | Deliberate variation |
+| --------------------------------------------------- | --------------------------------------------------------- | -------------------------------------------------------------------------- |
+| `component:Link` / native anchor | all three blocked destination prefixes remain inert | accepted destinations retain native anchor affordances |
+| `component:Link` / custom provider or `as` | either rejected `href`/`to` prevents router invocation | router owns accepted client-side navigation and receives unchanged objects |
+| `component:ClickableCard` / plain or modified click | every imperative or delegated exit uses the same decision | visible Card structure and nested-interactive handling remain local |
+| `component:Token` / link with remove action | surface activation and hidden link agree | remove action remains an independent sibling control |
+| `component:Markdown` / parsed link | blocked source does not become navigation | rejected source may render as text; resource policy remains separate |
+| navigation aggregate / member item | item destination uses the shared owner | tree, tab, breadcrumb, side-nav, top-nav, and menu semantics remain local |
+| `component:Citation` / linked source | blocked URL does not execute | native-anchor path and citation presentation remain local |
## Adoption and exceptions
-| Components or surface | Adoption | Current deviation or limitation |
-| ------------------------------------------------- | -------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
-| Markdown parsed and rendered links | shared contract through parser/render checks | parser and renderer maintain separate implementations; conformance must keep navigation decisions aligned |
-| Native React anchors, including Citation | platform owner | relies on the supported React DOM sanitizer rather than the Core predicate |
-| `useLinkComponent` custom provider and `as` paths | pending shared owner | current `main` forwards raw `href`/`to`; #5524 is the accepted implementation |
-| `useClickableContainer` imperative paths | pending shared owner | current `main` sends raw destinations to `window.open`/`window.location`; #5524 is the accepted implementation |
-| Components composing the two shared hooks | inherited | complete only when the relevant shared-owner gap above closes |
+| Components or surface | Required adoption |
+| ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
+| Markdown parsed and rendered links | Parsing and rendering preserve the shared navigation decision; image/resource policy remains separate (AV5). |
+| Native React anchors, including Citation | The full blocked-scheme rule holds; React DOM's `javascript:` protection alone is not sufficient. |
+| `useLinkComponent` custom provider and `as` paths | Both supplied destinations and supported structured forms, including `protocol`, obey the rule; rejection never invokes the router. |
+| `useClickableContainer` imperative paths | Same-tab, new-tab, modifier, middle-click, and delegated activation agree; non-navigation consumer callbacks remain available. |
+| Components composing the two shared hooks | Both delegated destinations and any separately rendered native anchor meet the full rule. |
-The pending rows are adoption gaps against FR1–FR6, not approved exceptions.
-When #5524 lands with exact-head evidence, this table must record shared adoption
-and include the new focused tests in `verified_by`.
+These are required outcomes, not a claim of completed verification. Adoption is
+complete only after exact-head evidence covers every applicable row. Neither a
+native-anchor React-only check, unchecked scheme-bearing fields, nor invoking a
+router with an undefined rejected destination is an approved exception.
## Verification map
-| Contract | Verification | Representative members and states | Mutation or failure expectation |
-| ------------------ | ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
-| FR1, FR2, FR6 | `useLinkComponent.test.tsx` | Link, Button, navigation members; provider and `as`; `href` and explicit `to` | A custom link receives a blocked destination or rest-prop order restores it |
-| FR1, FR3, FR4, FR5 | focused `useClickableContainer` tests required by `spec:AST-005` | ClickableCard and Token; plain, target, modified, middle click | A blocked imperative call occurs or an ordinary destination loses an activation mode |
-| FR4, FR5 | `parser.test.ts` and `Markdown.test.tsx` | parsed links, reference links, autolinks, mixed case, controls, relative and ordinary schemes | Markdown accepts a blocked scheme or rejects an ordinary navigation destination |
-| FR1, IR3 | source/member audit required by `spec:AST-005` | every caller-controlled Core navigation destination | A new sink or destination-bearing component ships outside this member snapshot |
-| FR7, FR8 | member-focused behavior and resource suites | disabled link modes; Markdown links versus images; Citation link versus image | Destination rejection changes disabled semantics or navigation policy silently becomes resource policy |
+| Contract | Verification | Representative members and states | Mutation or failure expectation |
+| ------------------ | ------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| FR4, FR5 | `safeUrl.test.ts` | string and structured destinations; mixed case; controls; relative, fragment, protocol-relative, ordinary, safe custom schemes, and `data:image/*`; separate `protocol` | The shared rule accepts a blocked destination or rejects an ordinary one, including when a protocol is separate from its pathname. |
+| FR1, FR2, FR6 | `useLinkComponent.test.tsx` and `apps/docsite/src/__tests__/link-navigation.test.ts` | native Link, Button, navigation members; provider and `as`; safe/rejected `href` and `to` in either combination; structured destinations and object identity | A rejected destination invokes the router (including with `undefined` or fallback), an accepted object loses identity, or a real router throws while rendering inert content. |
+| FR1, FR3, FR4, FR5 | `useClickableContainer.test.tsx` and real Chromium navigation coverage | ClickableCard and Token shapes; native Link; plain, `_blank`, Cmd/Ctrl-click, middle-click, delegated activation; accepted downloads | A rejected destination remains activatable, a blocked native, imperative, or delegated navigation occurs, or an accepted destination loses an activation mode. |
+| FR4, FR5 | `parser.test.ts`, `Markdown.test.tsx`, and `Markdown.renderBoundary.test.tsx` | parsed, reference, autolink, and transformed built-in links; mixed case; controls; ordinary schemes; `data:image/*` links versus images | Markdown accepts a blocked scheme, rejects an ordinary navigation destination, applies resource policy to a link, or renders a rejected node as navigation. |
+| FR1, IR3 | source/member audit required by `spec:AST-005` | every caller-controlled Core navigation destination | A new sink or destination-bearing component ships outside this member snapshot |
+| FR7, FR8 | member-focused behavior and resource suites | disabled link modes; Markdown links versus images; Citation link versus image | Destination rejection changes disabled semantics or navigation policy silently becomes resource policy |
## Decision links
diff --git a/docs/specs/AST-005/spec.md b/docs/specs/AST-005/spec.md
index d3b23c1080..658f2b5863 100644
--- a/docs/specs/AST-005/spec.md
+++ b/docs/specs/AST-005/spec.md
@@ -37,18 +37,18 @@ matter which component drew it, whether navigation is native or imperative, and
whether a framework router replaced the native anchor. Component composition
must not create a path around the shared rule.
-This spec accepts the shared navigation-destination contract. Current `main`
-already protects Markdown and native React anchors, but custom `LinkProvider`
-components and `useClickableContainer` imperative navigation do not yet apply the
-same rule. `family:navigation-destinations` records those adoption gaps until the
-implementation and verification land.
+This spec accepts the shared navigation-destination contract.
+`family:navigation-destinations` records adoption across native, custom-router,
+imperative, and Markdown navigation. Acceptance of the contract does not by
+itself establish implementation or exact-head verification.
## Non-goals
- Validating URL syntax, requiring absolute URLs, or restricting destinations to
an allowlist of hosts.
-- Defining policy for image, media, download, CSS, fetch, or other embedded
- resource URLs. Those sinks have different capabilities and content-type risks.
+- Defining content policy for image, media, downloaded files, CSS, fetch, or
+ other embedded resource URLs. Those sinks have different capabilities and
+ content-type risks; downloads from accepted link destinations stay supported.
- Sanitizing caller-owned JSX, custom Markdown plugin output, or arbitrary
consumer callbacks after control has left Astryx.
- Replacing Content Security Policy, router authorization, server validation, or
@@ -74,21 +74,30 @@ implementation and verification land.
target, modifier-key, or pointer-button differences can select another sink.
- **FR4 — Ordinary destinations keep working.** Relative paths, same-document
fragments, protocol-relative URLs, and ordinary schemes such as `http:`,
- `https:`, `mailto:`, and `tel:` MUST retain their existing navigation behavior.
- This contract does not rewrite, resolve, or host-filter accepted destinations.
-- **FR5 — Native, custom, and imperative paths are all covered.** The contract
+ `https:`, `mailto:`, `tel:`, and safe custom schemes MUST retain their existing
+ navigation behavior, including downloads from accepted destinations. This
+ contract does not rewrite, resolve, or host-filter accepted destinations.
+ Accepted structured router destinations MUST retain their object identity.
+- **FR5 — Native, custom, and imperative paths are all covered.** The full rule
MUST hold for React DOM anchors, a custom component supplied through
`LinkProvider` or an `as` seam, and imperative exits including `window.open`
- and `window.location`. Middle-click and Cmd/Ctrl-click are not exceptions.
+ and `window.location`. React DOM's own sanitizer is not a native-anchor
+ exception. Middle-click and Cmd/Ctrl-click are not exceptions either.
- **FR6 — Rejection fails closed at the navigation boundary.** A blocked
- destination MUST NOT be handed to a navigation-capable custom-router prop or
- imperative browser API. The component MAY preserve non-navigation rendering
- and consumer callbacks when doing so cannot activate the rejected destination.
+ destination MUST render inertly and MUST NOT reach an imperative browser API.
+ A custom router MUST NOT be invoked for a rejected destination, including with
+ `undefined` substituted for the rejected value. The component MAY preserve
+ non-navigation rendering and consumer callbacks when doing so cannot activate
+ the rejected destination.
- **FR7 — Router destination props are independent sinks.** When a custom link
component can receive both `href` and `to`, each supplied value MUST pass the
- rule independently. An explicit safe `to` MAY retain its documented precedence;
- an unsafe explicit `to` MUST NOT ride through a rest-prop spread or fall back to
- an unrelated unchecked value.
+ rule independently. If either is rejected, the result MUST be inert: no custom
+ router invocation and no fallback to the other destination, even if it is safe.
+ When both are accepted, an explicit `to` retains its documented precedence.
+ Supported structured destinations MUST obey the same rule, including every
+ scheme-bearing `href`, `pathname`, or `protocol` field and the destination
+ those fields form. A separate protocol or an unchecked field MUST NOT provide
+ a path around the rule. Accepted fields and object identity remain unchanged.
- **FR8 — Parser and rendering checks agree for navigation.** Markdown parsing,
Markdown link rendering, and shared Core navigation plumbing MUST reject the
same blocked navigation schemes after the same normalization. Markdown MAY use
@@ -99,9 +108,11 @@ implementation and verification land.
component-local blocked-scheme lists. Parser-local implementations MAY remain
separate only while conformance tests pin the same navigation matrix.
- **IR2 — Every distinct sink has mutation-sensitive coverage.** Verification
- MUST fail when the guard is removed from custom `href`, custom `to`, new-tab,
+ MUST fail when the guard is removed from native anchors, custom `href`, custom
+ `to`, supported structured destinations (including `protocol`), new-tab,
modified-click, middle-click, plain imperative navigation, or Markdown link
- parsing/rendering.
+ parsing/rendering. Rejected-router coverage MUST fail if the custom component
+ is invoked with `undefined` or another destination used as fallback.
- **IR3 — New navigation surfaces join the family.** A new component or hook that
accepts a caller-controlled navigation destination MUST join
`family:navigation-destinations` and reuse the shared owner before shipping.
@@ -113,10 +124,12 @@ implementation and verification land.
- Unsupported behavior: a custom component that ignores the filtered destination
props or manufactures a destination from other caller data is outside the
guarantee; Astryx MUST NOT claim that caller-owned behavior is sanitized.
-- Browser evidence: real Chromium verifies that blocked native and imperative
- destinations do not execute and that ordinary relative, external, modified,
- and middle-click navigation remains available. Unit integration tests verify
- custom router props without requiring a particular router package.
+- Browser evidence: real Chromium verifies that every blocked scheme remains
+ inert on native and imperative paths and that ordinary relative, external,
+ modified, middle-click, and download behavior remains available. Unit
+ integration tests verify custom router handoff and object identity; real
+ framework SSR verifies that rejection renders without invoking a router that
+ requires a destination.
## Current-state impact
@@ -125,39 +138,32 @@ Its membership covers every current Core component that accepts or derives a
navigation destination, including aggregate component records whose public
members own the actual `href`.
-Current `main` has three implementations:
+Implementation and verification must cover:
-1. React DOM protects native anchor `href` values.
-2. Markdown checks parsed and rendered destinations before creating links.
-3. Custom `LinkProvider` components and `useClickableContainer` imperative exits
- currently receive raw destinations; this is the gap addressed by #5524.
+1. the full blocked-scheme rule on native anchors, not just React DOM's own
+ `javascript:` protection;
+2. custom `href` and `to`, including supported structured destinations and their
+ separate `protocol`, with inert rendering whenever either value is rejected;
+3. every imperative and delegated activation while preserving accepted
+ destinations and consumer callbacks;
+4. conformant Markdown navigation with separate embedded-resource policy; and
+5. exact-head evidence before recording completed family adoption.
-Implementation of this accepted spec must:
-
-1. add one shared Core navigation predicate for custom-link and imperative exits;
-2. apply it to `href` and explicit `to` before custom link delegation;
-3. apply it before every `window.open` and `window.location` assignment in
- `useClickableContainer`;
-4. preserve the existing safe ordinary-destination behavior and the delegated
- `interactiveRef.click()` path;
-5. keep Markdown's navigation rule conformant while leaving embedded-resource
- policy separate; and
-6. update `family:navigation-destinations` from partial adoption to shared
- adoption when exact-head verification is green.
-
-No component-local public prop is added. Consumer documentation should state the
-shared outcome where a component documents an `href` or router seam; it should
-link to the shared rule rather than reproduce a scheme list in every prop row.
+No component-local public prop is added. Exceptional behavior belongs in
+caller-owned custom rendering outside this safe-navigation contract, not in a
+`LinkProvider` or `as` bypass. Consumer documentation should state the shared
+outcome where a component documents an `href` or router seam; it should link to
+the shared rule rather than reproduce a scheme list in every prop row.
## Verification
-| Contract | Verification | Representative states | Mutation or failure expectation |
-| ------------------ | -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
-| FR2, FR3, FR4, FR8 | Shared predicate and Markdown parser/render suites | mixed case; embedded controls; relative/hash; http(s); mailto/tel; blocked schemes | Removing normalization or changing one blocked prefix makes the navigation matrices disagree |
-| FR5, FR6, FR7 | `useLinkComponent` integration tests | native anchor; provider component; `as`; safe/unsafe `href`; safe/unsafe explicit `to` | A blocked value reaches `href` or `to`, or an ordinary explicit `to` loses precedence |
-| FR1, FR3, FR5, FR6 | `useClickableContainer` integration tests | plain click; `_blank`; Cmd/Ctrl-click; middle-click; delegated interactive ref | A blocked value reaches `window.open`/`window.location`, or an ordinary navigation path stops working |
-| FR1, IR1, IR3 | Family membership and source-usage audit | every current `useLinkComponent`, `useClickableContainer`, Markdown, and direct native-anchor destination owner | A new caller-controlled navigation sink ships outside the family or duplicates a local rule |
-| Browser contract | Real Chromium probe | native anchor, custom-router stand-in, imperative same-tab/new-tab, modified and middle click | Script executes, blocked navigation occurs, or ordinary browser affordances regress |
+| Contract | Verification | Representative states | Mutation or failure expectation |
+| ------------------ | ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| FR2, FR3, FR4, FR8 | Shared predicate and Markdown parser/render suites | mixed case; embedded controls; relative/hash; http(s); mailto/tel; safe custom schemes; downloads; blocked schemes | Removing normalization or changing one blocked prefix makes the navigation matrices disagree |
+| FR5, FR6, FR7 | `useLinkComponent` integration tests and framework SSR tests | native anchor; provider; `as`; safe/rejected `href` and `to` in either combination; structured `pathname`/`href`/`protocol`; accepted object identity | A rejected destination invokes the router, including with `undefined` or a safe fallback; accepted destinations lose identity or precedence; SSR throws |
+| FR1, FR3, FR5, FR6 | `useClickableContainer` integration tests | plain click; `_blank`; Cmd/Ctrl-click; middle-click; delegated interactive ref | A blocked value reaches `window.open`/`window.location`, or an ordinary navigation path stops working |
+| FR1, IR1, IR3 | Family membership and source-usage audit | every current `useLinkComponent`, `useClickableContainer`, Markdown, and direct native-anchor destination owner | A new caller-controlled navigation sink ships outside the family or duplicates a local rule |
+| Browser contract | Real Chromium probe | all blocked prefixes on native anchors; custom-router stand-in; imperative same-tab/new-tab; modified and middle click; accepted destinations and downloads | Script executes, blocked navigation occurs, a rejected destination gains link activation, or ordinary browser affordances regress |
### Completion criteria
@@ -165,7 +171,8 @@ This spec moves from `accepted` to `shipped` only when:
- every adoption gap in `family:navigation-destinations` is closed or documented
as an explicit owner-approved exception;
-- exact-head tests cover each distinct custom and imperative sink;
+- exact-head tests cover native anchors, structured router destinations, inert
+ router rejection, and each distinct imperative and Markdown navigation sink;
- a source/member audit finds no caller-controlled Core navigation exit outside
the family; and
- consumer docs describe the shared outcome without implying that embedded
@@ -195,9 +202,9 @@ it does not inspect props handed to a custom router and does not mediate
Navigation destinations and embedded resources are separate sink families. This
spec blocks executable document schemes for navigation without deciding which
-`data:` media types, image sources, downloads, or fetched resources are allowed.
-Markdown may therefore reject a broader resource set while matching the shared
-navigation matrix.
+image sources, downloaded content, or fetched resources are allowed. Downloads
+from accepted navigation destinations keep working. Markdown may therefore
+reject a broader resource set while matching the shared navigation matrix.
Rejected: one undifferentiated “safe URL” boolean for every URL-shaped value.
That hides material differences between navigating a document and embedding or
diff --git a/packages/core/src/Button/Button.doc.mjs b/packages/core/src/Button/Button.doc.mjs
index fbb31d7d3b..962fd62cd7 100644
--- a/packages/core/src/Button/Button.doc.mjs
+++ b/packages/core/src/Button/Button.doc.mjs
@@ -210,7 +210,7 @@ export const docs = {
name: 'href',
type: 'string',
description:
- 'When provided, renders the button as a link element (<a> or custom link component).',
+ 'When provided, renders the button as a link element (<a> or custom link component). The destination follows the shared navigation rule described on the Link `href` prop.',
},
{
name: 'as',
diff --git a/packages/core/src/Citation/Citation.doc.mjs b/packages/core/src/Citation/Citation.doc.mjs
index 65f5b7bda5..d727ba6e7c 100644
--- a/packages/core/src/Citation/Citation.doc.mjs
+++ b/packages/core/src/Citation/Citation.doc.mjs
@@ -71,7 +71,7 @@ export const docs = {
name: 'source',
type: 'CitationSource',
description:
- 'The citation source object containing title, url, an optional image src, and an optional icon node.',
+ 'The citation source object containing title, url, an optional image src, and an optional icon node. The url follows the shared navigation rule described on the Link `href` prop; rejected destinations leave the citation visible without navigation. Image src uses separate resource handling.',
required: true,
},
{
@@ -122,7 +122,7 @@ export const docsDense = {
},
propDescriptions: {
source:
- 'citation source object with title, url, optional image src, and optional icon node.',
+ 'citation source with title, url, optional image src, and optional icon. url follows the Link href navigation rule; rejected destinations stay visible without navigation. Image src handling is separate.',
number: 'display index for this citation.',
variant: 'display style: label chip with source title or compact numbered badge.',
},
diff --git a/packages/core/src/Citation/Citation.test.tsx b/packages/core/src/Citation/Citation.test.tsx
index 9d01f7f508..21ba9e9e54 100644
--- a/packages/core/src/Citation/Citation.test.tsx
+++ b/packages/core/src/Citation/Citation.test.tsx
@@ -36,6 +36,23 @@ function atomicClasses(style: (typeof probe)[keyof typeof probe]): string[] {
describe('Citation', () => {
const source = {title: 'Example Source', url: 'https://example.com'};
+ it.each([
+ 'javascript:alert(1)',
+ 'vbscript:MsgBox(1)',
+ 'data:text/html,<b>x</b>',
+ 'java\nscript:alert(1)',
+ ])('renders rejected citation URL %s without navigation', url => {
+ const {container} = render(
+ <>
+ <Citation source={{title: 'Source', url}} number={1} />
+ <Citation source={{title: 'Source', url}} number={1} variant="number" />
+ </>,
+ );
+ expect(container.querySelector('a')).toBeNull();
+ expect(container.querySelector('[href]')).toBeNull();
+ expect(container.textContent).toBe('Source1');
+ });
+
it('renders the source title as a link in the label variant', () => {
render(<Citation source={source} number={1} data-testid="citation" />);
const el = screen.getByTestId('citation');
diff --git a/packages/core/src/Citation/Citation.tsx b/packages/core/src/Citation/Citation.tsx
index 0b185df321..d2465743bb 100644
--- a/packages/core/src/Citation/Citation.tsx
+++ b/packages/core/src/Citation/Citation.tsx
@@ -4,7 +4,7 @@
/**
* @file Citation.tsx
- * @input Uses React, StyleX, theme tokens
+ * @input Uses React, StyleX, theme tokens, and the shared navigation policy
* @output Exports Citation component for inline citation references
* @position Core implementation; consumed by index.ts
*
@@ -30,6 +30,7 @@ import {
easeVars,
} from '../theme/tokens.stylex';
import {mergeProps} from '../utils';
+import {isSafeUrl} from '../utils/safeUrl';
import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
import {useTranslator} from '../i18n';
@@ -189,7 +190,8 @@ export function Citation({
}: CitationProps): React.ReactElement {
const t = useTranslator();
const title = source.title ?? String(number);
- const href = source.url;
+ const href =
+ source.url != null && isSafeUrl(source.url) ? source.url : undefined;
// Resolve the source icon. A non-string `icon` node renders as-is (an Astryx
// <Icon>, SVG, avatar, etc.). Otherwise fall back to an image URL: `src`, or
diff --git a/packages/core/src/ClickableCard/ClickableCard.doc.mjs b/packages/core/src/ClickableCard/ClickableCard.doc.mjs
index a3acd9d41a..1f75d7ec2e 100644
--- a/packages/core/src/ClickableCard/ClickableCard.doc.mjs
+++ b/packages/core/src/ClickableCard/ClickableCard.doc.mjs
@@ -22,7 +22,7 @@ export const docs = {
props: [
{name: 'label', type: 'string', description: 'Accessibility label.', required: true},
{name: 'onClick', type: '(event: MouseEvent) => void', description: 'Click handler: fires on card surface only.'},
- {name: 'href', type: 'string', description: 'Navigation URL.'},
+ {name: 'href', type: 'string', description: 'Navigation URL. Plain, new-tab, Cmd/Ctrl-click, and middle-click activation all follow the shared navigation rule described on the Link `href` prop.'},
{name: 'target', type: 'string', description: 'Link target.', default: "'_self'"},
{name: 'isDisabled', type: 'boolean', description: 'Disables the card.', default: 'false'},
{name: 'children', type: 'ReactNode', description: 'Card content.'},
@@ -69,7 +69,7 @@ export const docsDense = {
propDescriptions: {
label: 'accessibility label',
onClick: 'click handler: fires on card surface only',
- href: 'navigation URL',
+ href: 'navigation URL; every activation follows the shared navigation rule (see Link href)',
target: 'link target',
isDisabled: 'disables card',
padding: 'inner padding',
diff --git a/packages/core/src/Item/Item.doc.mjs b/packages/core/src/Item/Item.doc.mjs
index d3ae0344c3..f475b1a3c2 100644
--- a/packages/core/src/Item/Item.doc.mjs
+++ b/packages/core/src/Item/Item.doc.mjs
@@ -43,7 +43,7 @@ export const docs = {
{name: 'layout', type: "'stacked' | 'inline'", description: 'How the label and description sit together. stacked puts the description on its own line below the label; inline keeps both on one line, description ellipsizing first, so the row fits a fixed-height host.', default: "'stacked'"},
{name: 'onClick', type: '(event: MouseEvent) => void', description: 'Click handler. Makes the item clickable with button semantics.'},
{name: 'interactiveRef', type: 'RefObject<HTMLElement | null>', description: 'Ref to a nested control (e.g. a checkbox in startContent) that owns the item\'s keyboard access and action. The row becomes an enlarged click/tap target that delegates surface clicks to it (useClickableContainer) and renders no invisible button/anchor, so the row adds no second tab stop (WCAG 4.1.2). Mutually exclusive with onClick/href; those are ignored when set.'},
- {name: 'href', type: 'string', description: 'Link URL. Makes the item a link via an invisible anchor element.'},
+ {name: 'href', type: 'string', description: 'Link URL. Makes the item a link via an invisible anchor element. The destination follows the shared navigation rule described on the Link `href` prop.'},
{name: 'target', type: "'_blank' | '_self'", description: 'Link target. Only used with href. target="_blank" automatically adds noopener noreferrer.'},
{name: 'rel', type: 'string', description: 'Link relationship tokens. noopener noreferrer are merged automatically for target="_blank".'},
{name: 'isHighlighted', type: 'boolean', description: 'Highlighted state (hover/keyboard focus appearance).', default: 'false'},
@@ -167,7 +167,7 @@ export const docsDense = {
onClick: 'Click handler; enables button semantics.',
interactiveRef:
'Ref to a nested control that owns the item\'s keyboard access/action; row delegates surface clicks to it (useClickableContainer), no invisible button/anchor, no second tab stop (WCAG 4.1.2). Mutually exclusive with onClick/href.',
- href: 'Link URL; enables anchor semantics.',
+ href: 'Link URL; enables anchor semantics. Follows the shared navigation rule (see Link href).',
target:
'Link target, only with href. target="_blank" auto-adds noopener noreferrer.',
rel: 'Link relationship tokens. noopener noreferrer are merged for target="_blank".',
diff --git a/packages/core/src/Link/Link.doc.mjs b/packages/core/src/Link/Link.doc.mjs
index 991abcef05..326a3a8c0f 100644
--- a/packages/core/src/Link/Link.doc.mjs
+++ b/packages/core/src/Link/Link.doc.mjs
@@ -38,7 +38,8 @@ export const docs = {
{
name: 'href',
type: 'string',
- description: 'Link destination URL',
+ description:
+ 'Link destination URL. Astryx-owned links and clickable surfaces block javascript:, vbscript:, and data:text/html after control-character removal, outer-whitespace trimming, and case-insensitive scheme inspection. The same rule covers native anchors, custom routers, Markdown links, and every activation method. Relative paths, fragments, protocol-relative URLs, HTTP(S), mailto, tel, safe custom schemes, and accepted downloads keep their existing behavior. A rejected destination renders inertly without invoking a custom router. There is no bypass prop; exceptional behavior requires caller-owned custom rendering outside this guarantee. Images and other resource URLs have separate policies.',
},
{
name: 'hasUnderline',
@@ -151,7 +152,8 @@ export const docs = {
{
name: 'component',
type: 'LinkComponentType',
- description: 'Component to use for all link elements',
+ description:
+ 'Component to use for all link elements. It receives accepted `href` and `to` values under the shared navigation rule described on the Link `href` prop. Supported structured destinations, including their `protocol`, are checked without changing object identity. If either supplied destination is rejected, Astryx renders inert content without invoking this component; it does not pass undefined or fall back to the other destination.',
required: true,
},
{
@@ -355,7 +357,7 @@ export const docsDense = {
propDescriptions: {
as: 'Custom component to render instead of <a>',
label: 'Accessible label (aria-label). Only for non-text content like icon-only links.',
- href: 'Link destination URL',
+ href: 'Link destination URL. Shared rule blocks javascript:, vbscript:, data:text/html after scheme normalization on every Astryx-owned navigation path. Ordinary URLs, fragments, safe custom schemes, and accepted downloads are preserved. Rejected => inert, no custom router. No bypass prop; exceptional caller-owned rendering is outside the guarantee. Image/resource policy is separate.',
hasUnderline: 'Always show underline',
isDisabled: 'Disables link',
isExternalLink: 'Opens new tab w/ external icon and safe rel tokens',
@@ -376,7 +378,7 @@ export const docsDense = {
description:
'Provider setting default link component for all Astryx links in subtree.',
propDescriptions: {
- component: 'Component for all link elements',
+ component: 'Component for all link elements. Accepted href/to follow the Link href rule; structured fields including protocol are checked, preserving identity. Either rejected => inert content, no router invocation or fallback.',
children: 'Subtree',
},
},
diff --git a/packages/core/src/Link/LinkProvider.doc.mjs b/packages/core/src/Link/LinkProvider.doc.mjs
index 9c78b8d46f..e682b20140 100644
--- a/packages/core/src/Link/LinkProvider.doc.mjs
+++ b/packages/core/src/Link/LinkProvider.doc.mjs
@@ -13,7 +13,7 @@ export const docs = {
description: 'Wraps your app to replace the default <a> tag with a framework-specific link component (e.g. Next.js Link) for client-side routing across all Astryx components.',
},
props: [
- {name: 'component', type: 'LinkComponentType', required: true, description: 'Link component to use for all link elements in the subtree (e.g. Next.js Link).'},
+ {name: 'component', type: 'LinkComponentType', required: true, description: 'Link component to use for all link elements in the subtree (e.g. Next.js Link). It receives accepted `href` and `to` values under the shared navigation rule described on the Link `href` prop. Supported structured destinations, including their `protocol`, are checked without changing object identity. If either supplied destination is rejected, Astryx renders inert content without invoking this component; it does not pass undefined or fall back to the other destination.'},
{name: 'children', type: 'ReactNode', required: true, description: 'Content to render with the link provider.'},
],
};
@@ -25,6 +25,6 @@ export const docsDense = {
description: 'Wraps app to replace default <a> tag w/ framework-specific link component (e.g. Next.js Link) for client-side routing across all Astryx components.',
},
propDescriptions: {
- component: 'link component for all link elements in subtree (e.g. Next.js Link)',
+ component: 'link component for all link elements in subtree (e.g. Next.js Link). Accepted href/to follow the Link href rule; structured fields including protocol are checked, preserving identity. Either rejected => inert content, no router invocation or fallback.',
},
};
diff --git a/packages/core/src/Link/__tests__/Link.navigation.a11y.chromium.spec.ts b/packages/core/src/Link/__tests__/Link.navigation.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..3beab5bdd0
--- /dev/null
+++ b/packages/core/src/Link/__tests__/Link.navigation.a11y.chromium.spec.ts
@@ -0,0 +1,261 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Link.navigation.a11y.chromium.spec.ts
+ * @input Built Storybook navigation fixture and real Chromium activation
+ * @output Blocked-scheme and accepted-navigation evidence across every sink
+ * @position Browser proof for the shared navigation-destination contract
+ */
+
+import {expect, test, type Page} from '@playwright/test';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+let storybook: StaticServer;
+const storyId = 'core-link-navigation--destinations';
+
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+async function mount(page: Page, href: string) {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=${storyId}&viewMode=story`,
+ );
+ await expect(page.getByTestId('navigation-fixture')).toBeVisible();
+ await page.evaluate(
+ ({storyId, href}) => {
+ const channel = (
+ window as unknown as {
+ __STORYBOOK_ADDONS_CHANNEL__: {
+ emit: (event: string, payload: unknown) => void;
+ };
+ }
+ ).__STORYBOOK_ADDONS_CHANNEL__;
+ channel.emit('updateStoryArgs', {storyId, updatedArgs: {href}});
+ },
+ {storyId, href},
+ );
+ await expect(page.getByTestId('navigation-fixture')).toHaveAttribute(
+ 'data-destination',
+ href,
+ );
+}
+
+const blocked = [
+ 'javascript:window.__navigationExecuted=true',
+ 'vbscript:MsgBox(1)',
+ 'data:text/html,<script>window.__navigationExecuted=true</script>',
+ ' \u0000JaVa\tsCrIpT:window.__navigationExecuted=true',
+];
+
+for (const href of blocked) {
+ test(`rejected ${JSON.stringify(href)} is inert across native, router, Markdown, and imperative paths`, async ({
+ page,
+ context,
+ }) => {
+ await mount(page, href);
+ const originalUrl = page.url();
+ await page.evaluate(() => {
+ (
+ window as unknown as {__navigationExecuted: boolean}
+ ).__navigationExecuted = false;
+ });
+ const pagesBefore = context.pages().length;
+ for (const id of [
+ 'native',
+ 'provider',
+ 'as',
+ 'structured',
+ 'citation',
+ 'download',
+ ]) {
+ const target = page.getByTestId(id);
+ await expect(target).not.toHaveAttribute('href');
+ await expect(target).not.toHaveAttribute('data-router');
+ await target.click();
+ await target.click({button: 'middle'});
+ }
+ await expect(page.getByTestId('markdown').locator('a')).toHaveCount(0);
+ await expect(page.getByTestId('delegated').locator('a[href]')).toHaveCount(
+ 0,
+ );
+ for (const id of ['imperative', 'imperative-blank', 'delegated']) {
+ const target =
+ id === 'delegated'
+ ? page.getByText('Delegated card surface', {exact: true})
+ : page.getByTestId(id);
+ await target.click();
+ await target.click({modifiers: ['Control']});
+ await target.click({modifiers: ['Meta']});
+ await target.click({button: 'middle'});
+ }
+ // Drain browser activation tasks before checking that no sink fired.
+ await page.evaluate(
+ async () =>
+ new Promise<void>(resolve =>
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
+ ),
+ );
+ expect(page.url()).toBe(originalUrl);
+ expect(context.pages()).toHaveLength(pagesBefore);
+ expect(
+ await page.evaluate(
+ () =>
+ (window as unknown as {__navigationExecuted: boolean})
+ .__navigationExecuted,
+ ),
+ ).toBe(false);
+ });
+}
+
+test('ordinary schemes keep native attributes, custom routing, and downloads', async ({
+ page,
+}) => {
+ for (const href of [
+ '#fragment',
+ '/relative',
+ 'https://example.com/docs',
+ 'http://example.com/docs',
+ 'mailto:[email protected]',
+ 'tel:+1234567890',
+ 'custom:document',
+ 'data:text/plain,download',
+ ]) {
+ await mount(page, href);
+ for (const id of [
+ 'native',
+ 'provider',
+ 'as',
+ 'structured',
+ 'citation',
+ 'download',
+ ]) {
+ await expect(page.getByTestId(id)).toHaveAttribute('href', href);
+ }
+ for (const id of ['provider', 'as', 'structured']) {
+ await expect(page.getByTestId(id)).toHaveAttribute('data-router', 'true');
+ }
+ await expect(page.getByTestId('download')).toHaveAttribute(
+ 'download',
+ 'note.txt',
+ );
+ await expect(page.getByTestId('markdown').locator('a')).toHaveAttribute(
+ 'href',
+ href,
+ );
+ }
+});
+
+for (const id of [
+ 'native',
+ 'provider',
+ 'as',
+ 'structured',
+ 'imperative',
+ 'delegated',
+]) {
+ test(`${id} retains real same-tab navigation`, async ({page}) => {
+ const href = '/navigation-destination?source=' + id;
+ await page.route('**/navigation-destination?*', async route =>
+ route.fulfill({
+ contentType: 'text/html',
+ body: '<h1>Destination reached</h1>',
+ }),
+ );
+ await mount(page, href);
+ const target =
+ id === 'delegated'
+ ? page.getByText('Delegated card surface', {exact: true})
+ : page.getByTestId(id);
+ await target.click();
+ await expect(page).toHaveURL(`${storybook.origin}${href}`);
+ await expect(
+ page.getByRole('heading', {name: 'Destination reached'}),
+ ).toBeVisible();
+ });
+}
+
+for (const activation of ['blank', 'control', 'meta', 'middle'] as const) {
+ test(`imperative ${activation} retains real new-tab navigation`, async ({
+ page,
+ context,
+ }) => {
+ const href = `${storybook.origin}/navigation-destination?source=${activation}`;
+ await context.route('**/navigation-destination?*', async route =>
+ route.fulfill({
+ contentType: 'text/html',
+ body: '<h1>Destination reached</h1>',
+ }),
+ );
+ await mount(page, href);
+ const originalUrl = page.url();
+ const opened = context.waitForEvent('page');
+ await page
+ .getByTestId(activation === 'blank' ? 'imperative-blank' : 'imperative')
+ .click({
+ button: activation === 'middle' ? 'middle' : 'left',
+ modifiers:
+ activation === 'control'
+ ? ['Control']
+ : activation === 'meta'
+ ? ['Meta']
+ : [],
+ });
+ const popup = await opened;
+ await expect(popup).toHaveURL(href);
+ await expect(
+ popup.getByRole('heading', {name: 'Destination reached'}),
+ ).toBeVisible();
+ expect(page.url()).toBe(originalUrl);
+ await popup.close();
+ });
+}
+
+test('native anchors retain real downloads and same-document fragments', async ({
+ page,
+}) => {
+ await mount(page, 'data:text/plain,download');
+ const downloadEvent = page.waitForEvent('download');
+ await page.getByTestId('download').click();
+ const download = await downloadEvent;
+ expect(download.suggestedFilename()).toBe('note.txt');
+ expect(await download.failure()).toBeNull();
+ await mount(page, '#destination');
+ await page.getByTestId('native').click();
+ await expect(page).toHaveURL(/#destination$/);
+});
+
+test('native anchors retain real middle-click and external target navigation', async ({
+ page,
+ context,
+}) => {
+ const href = 'https://example.com/navigation-destination';
+ await context.route(href, async route =>
+ route.fulfill({
+ contentType: 'text/html',
+ body: '<h1>External destination</h1>',
+ }),
+ );
+ for (const id of ['native', 'citation']) {
+ await mount(page, href);
+ const opened = context.waitForEvent('page');
+ await page
+ .getByTestId(id)
+ .click({button: id === 'native' ? 'middle' : 'left'});
+ const popup = await opened;
+ await expect(popup).toHaveURL(href);
+ await expect(
+ popup.getByRole('heading', {name: 'External destination'}),
+ ).toBeVisible();
+ await popup.close();
+ }
+});
diff --git a/packages/core/src/Link/useLinkComponent.test.tsx b/packages/core/src/Link/useLinkComponent.test.tsx
index a9ae2dc21d..729830e9af 100644
--- a/packages/core/src/Link/useLinkComponent.test.tsx
+++ b/packages/core/src/Link/useLinkComponent.test.tsx
@@ -208,6 +208,339 @@ describe('useLinkComponent — to prop', () => {
});
});
+// =============================================================================
+// href scheme rule
+// =============================================================================
+
+describe('useLinkComponent — href scheme rule', () => {
+ // Kept in a const so the JSX stays lint-clean — the test is ABOUT this URL.
+ const scriptUrl = 'javascript:alert(1)';
+
+ function HrefConsumer({href}: {href: string}) {
+ const LinkComponent = useLinkComponent();
+ return (
+ <LinkComponent href={href} data-testid="resolved-link">
+ Link
+ </LinkComponent>
+ );
+ }
+
+ function propSpy() {
+ return vi.fn(
+ ({
+ children,
+ ...props
+ }: {
+ children?: React.ReactNode;
+ [key: string]: unknown;
+ }) => (
+ <a data-testid="spy-link" href={props.href as string}>
+ {children}
+ </a>
+ ),
+ );
+ }
+
+ it('forwards ordinary hrefs to a custom component untouched', () => {
+ const spy = propSpy();
+ function SpyLink(props: {[key: string]: unknown}) {
+ return spy(props);
+ }
+ render(
+ <LinkProvider component={SpyLink}>
+ <HrefConsumer href="/docs/button" />
+ </LinkProvider>,
+ );
+ expect(spy).toHaveBeenCalledWith(
+ expect.objectContaining({href: '/docs/button', to: '/docs/button'}),
+ );
+ });
+
+ it('withholds a script-scheme href from a custom component (href and to alike)', () => {
+ const spy = propSpy();
+ function SpyLink(props: {[key: string]: unknown}) {
+ return spy(props);
+ }
+ render(
+ <LinkProvider component={SpyLink}>
+ {/* eslint-disable-next-line @eslint-react/dom-no-script-url -- the test proves this URL never navigates */}
+ <HrefConsumer href={scriptUrl} />
+ </LinkProvider>,
+ );
+ expect(spy).not.toHaveBeenCalled();
+ expect(screen.getByTestId('resolved-link')).not.toHaveAttribute('href');
+ });
+
+ it('an explicit `to` passes the same check instead of riding through ...rest', () => {
+ const spy = propSpy();
+ function SpyLink(props: {[key: string]: unknown}) {
+ return spy(props);
+ }
+ function ToConsumer({to}: {to: string}) {
+ const LinkComponent = useLinkComponent();
+ return (
+ <LinkComponent href="/fallback" to={to} data-testid="resolved-link">
+ Link
+ </LinkComponent>
+ );
+ }
+ render(
+ <LinkProvider component={SpyLink}>
+ {/* eslint-disable-next-line @eslint-react/dom-no-script-url -- the test proves this URL never reaches the router */}
+ <ToConsumer to={scriptUrl} />
+ </LinkProvider>,
+ );
+ expect(spy).not.toHaveBeenCalled();
+ expect(screen.getByTestId('resolved-link')).not.toHaveAttribute('href');
+ });
+
+ it('an ordinary explicit `to` keeps its precedence over href', () => {
+ const spy = propSpy();
+ function SpyLink(props: {[key: string]: unknown}) {
+ return spy(props);
+ }
+ function ToConsumer() {
+ const LinkComponent = useLinkComponent();
+ return (
+ <LinkComponent
+ href="/fallback"
+ to="/routed"
+ data-testid="resolved-link">
+ Link
+ </LinkComponent>
+ );
+ }
+ render(
+ <LinkProvider component={SpyLink}>
+ <ToConsumer />
+ </LinkProvider>,
+ );
+ expect(spy).toHaveBeenCalledWith(
+ expect.objectContaining({href: '/fallback', to: '/routed'}),
+ );
+ });
+});
+
+// =============================================================================
+// structured router `to`
+// =============================================================================
+
+describe('useLinkComponent — structured router `to`', () => {
+ const scriptUrl = 'javascript:alert(1)';
+
+ function propSpy() {
+ return vi.fn(
+ ({
+ children,
+ ...props
+ }: {
+ children?: React.ReactNode;
+ [key: string]: unknown;
+ }) => (
+ <a data-testid="spy-link" href={props.href as string}>
+ {children}
+ </a>
+ ),
+ );
+ }
+
+ function ToConsumer({to}: {to: unknown}) {
+ const LinkComponent = useLinkComponent();
+ return (
+ <LinkComponent href="/fallback" to={to} data-testid="resolved-link">
+ Link
+ </LinkComponent>
+ );
+ }
+
+ it('preserves a structured destination for the router (no crash, same object)', () => {
+ const spy = propSpy();
+ function SpyLink(props: {[key: string]: unknown}) {
+ return spy(props);
+ }
+ const to = {pathname: '/docs', search: '?q=1', hash: '#top'};
+ render(
+ <LinkProvider component={SpyLink}>
+ <ToConsumer to={to} />
+ </LinkProvider>,
+ );
+ expect(spy).toHaveBeenCalledWith(
+ expect.objectContaining({href: '/fallback', to}),
+ );
+ expect(spy.mock.calls[0][0].to).toBe(to);
+ });
+
+ it('preserves a structured destination that carries no pathname', () => {
+ const spy = propSpy();
+ function SpyLink(props: {[key: string]: unknown}) {
+ return spy(props);
+ }
+ const to = {search: '?page=2'};
+ render(
+ <LinkProvider component={SpyLink}>
+ <ToConsumer to={to} />
+ </LinkProvider>,
+ );
+ expect(spy).toHaveBeenCalledWith(expect.objectContaining({to}));
+ });
+
+ it('withholds a structured destination whose pathname is a script scheme', () => {
+ const spy = propSpy();
+ function SpyLink(props: {[key: string]: unknown}) {
+ return spy(props);
+ }
+ render(
+ <LinkProvider component={SpyLink}>
+ <ToConsumer to={{pathname: scriptUrl}} />
+ </LinkProvider>,
+ );
+ expect(spy).not.toHaveBeenCalled();
+ expect(screen.getByTestId('resolved-link')).not.toHaveAttribute('href');
+ });
+
+ it('withholds a structured destination whose href is a script scheme', () => {
+ const spy = propSpy();
+ function SpyLink(props: {[key: string]: unknown}) {
+ return spy(props);
+ }
+ render(
+ <LinkProvider component={SpyLink}>
+ <ToConsumer to={{href: scriptUrl}} />
+ </LinkProvider>,
+ );
+ expect(spy).not.toHaveBeenCalled();
+ expect(screen.getByTestId('resolved-link')).not.toHaveAttribute('href');
+ });
+});
+
+// =============================================================================
+// Shared native and router boundary
+// =============================================================================
+
+describe('useLinkComponent — rejected destinations are inert', () => {
+ function Consumer({
+ href,
+ to,
+ as,
+ onClick,
+ linkRef,
+ }: {
+ href?: unknown;
+ to?: unknown;
+ as?: LinkComponentType;
+ onClick?: () => void;
+ linkRef?: React.Ref<HTMLAnchorElement>;
+ }) {
+ const Component = useLinkComponent(as);
+ return (
+ <Component
+ href={href}
+ to={to}
+ ref={linkRef}
+ onClick={onClick}
+ className="consumer-class"
+ aria-label="Destination"
+ data-testid="destination">
+ Go
+ </Component>
+ );
+ }
+
+ for (const mode of ['native', 'provider', 'as'] as const) {
+ it.each([
+ {href: 'javascript:alert(1)'},
+ {href: 'vbscript:MsgBox(1)'},
+ {href: 'data:text/html,<b>x</b>'},
+ {href: 'java\nscript:alert(1)'},
+ {href: '/safe', to: 'javascript:alert(1)'},
+ {href: 'vbscript:MsgBox(1)', to: '/safe'},
+ {href: {protocol: 'javascript:', pathname: 'alert(1)'}},
+ {href: '/safe', to: {protocol: 'data:', pathname: 'text/html,x'}},
+ ])(`${mode}: rejects %j without calling a router`, props => {
+ const router = vi.fn(() => {
+ throw new Error('rejected router invoked');
+ });
+ const onClick = vi.fn();
+ const linkRef = vi.fn();
+ render(
+ <LinkProvider component={mode === 'provider' ? router : 'a'}>
+ <Consumer
+ {...props}
+ as={mode === 'as' ? router : undefined}
+ onClick={onClick}
+ linkRef={linkRef}
+ />
+ </LinkProvider>,
+ );
+ const node = screen.getByTestId('destination');
+ expect(router).not.toHaveBeenCalled();
+ expect(node.tagName).toBe('A');
+ expect(node).not.toHaveAttribute('href');
+ expect(node).not.toHaveAttribute('to');
+ expect(node).not.toHaveAttribute('aria-disabled');
+ expect(node).toHaveAttribute('aria-label', 'Destination');
+ expect(node).toHaveClass('consumer-class');
+ expect(linkRef.mock.calls[0][0]).toBe(node);
+ node.click();
+ expect(onClick).toHaveBeenCalledOnce();
+ });
+ }
+
+ it.each([
+ '/relative',
+ '#fragment',
+ 'https://example.com',
+ 'http://example.com',
+ 'mailto:[email protected]',
+ 'tel:+1234567890',
+ 'custom:document',
+ 'data:text/plain,download',
+ ])('preserves native href and download affordances for %s', href => {
+ function Download() {
+ const Component = useLinkComponent();
+ return (
+ <Component
+ href={href}
+ download="note.txt"
+ target="_blank"
+ rel="noopener"
+ data-testid="download">
+ Download
+ </Component>
+ );
+ }
+ render(<Download />);
+ const node = screen.getByTestId('download');
+ expect(node).toHaveAttribute('href', href);
+ expect(node).toHaveAttribute('download', 'note.txt');
+ expect(node).toHaveAttribute('target', '_blank');
+ expect(node).toHaveAttribute('rel', 'noopener');
+ });
+
+ it('preserves both structured prop identities and safe explicit precedence', () => {
+ const router = vi.fn<(props: {href?: unknown; to?: unknown}) => null>(
+ () => null,
+ );
+ const href = {
+ protocol: 'https:',
+ hostname: 'example.com',
+ pathname: '/docs',
+ };
+ const to = {pathname: '/next', search: '?q=1', hash: '#top'};
+ render(<Consumer as={router} href={href} to={to} />);
+ expect(router.mock.calls[0][0].href).toBe(href);
+ expect(router.mock.calls[0][0].to).toBe(to);
+ });
+
+ it('keeps the native node stable while accepted props update', () => {
+ const {rerender} = render(<Consumer href="/first" />);
+ const node = screen.getByTestId('destination');
+ rerender(<Consumer href="/second" />);
+ expect(screen.getByTestId('destination')).toBe(node);
+ expect(node).toHaveAttribute('href', '/second');
+ });
+});
+
// =============================================================================
// LinkProvider
// =============================================================================
diff --git a/packages/core/src/Link/useLinkComponent.ts b/packages/core/src/Link/useLinkComponent.ts
index ff3718fa85..13afd70dea 100644
--- a/packages/core/src/Link/useLinkComponent.ts
+++ b/packages/core/src/Link/useLinkComponent.ts
@@ -4,89 +4,61 @@
/**
* @file useLinkComponent.ts
- * @input React use, useMemo, createElement, forwardRef, LinkContext, LinkComponentType
- * @output Exports useLinkComponent hook
- * @position Hook for resolving the link component in Astryx components
+ * @input Per-component override, LinkProvider context, and navigation props
+ * @output Stable link component with destination checks and custom-router `to` injection
+ * @position Shared native and custom link boundary; rejected destinations render
+ * as destination-less anchors without invoking a router.
*
- * Resolution order: per-component `as` prop > LinkProvider context > native `<a>`.
- *
- * When the resolved component is a custom component (not native `<a>`),
- * wraps it to pass `to={href}` alongside `href`. This enables compatibility
- * with routers that use `to` (React Router, TanStack Router)
- * without requiring an adapter component.
- *
- * SYNC: When modified, update these files to stay in sync:
- * - /packages/core/src/Link/index.ts
- * - /packages/core/src/Link/Link.doc.mjs
+ * SYNC: Link.doc.mjs and LinkProvider.doc.mjs describe this boundary.
*/
import {use, useMemo, createElement} from 'react';
import {LinkContext} from './LinkContext';
+import {isSafeDestination} from '../utils/safeUrl';
import type {LinkComponentType} from './types';
-/**
- * Creates a wrapper component that passes both `href` and `to` props
- * to the underlying link component. This enables routers that use `to`
- * (React Router, TanStack Router) to work without an adapter.
- *
- * The wrapper is transparent: it forwards refs and all other props unchanged.
- * Native `<a>` elements ignore the unknown `to` prop harmlessly.
- */
-function createLinkWithTo(
- Component: LinkComponentType,
-): LinkComponentType {
- function LinkWithTo({
+function createSafeLink(Component: LinkComponentType): LinkComponentType {
+ function SafeLink({
href,
+ to,
ref,
...rest
}: {
- href?: string;
- to?: string;
+ href?: unknown;
+ to?: unknown;
ref?: React.Ref<unknown>;
}) {
- return createElement(Component, {ref, href, to: href, ...rest});
+ // An undefined destination can crash a router or resolve to the current
+ // route. Reject the whole handoff, not just one prop or a fallback value.
+ if (!isSafeDestination(href) || !isSafeDestination(to)) {
+ return createElement('a', {ref, ...rest});
+ }
+ if (Component === 'a') {
+ return createElement('a', {ref, ...rest, href});
+ }
+ return createElement(Component, {ref, ...rest, href, to: to ?? href});
}
- LinkWithTo.displayName = `LinkWithTo(${
+ SafeLink.displayName = `SafeLink(${
typeof Component === 'string'
? Component
: Component.displayName || Component.name || 'Component'
})`;
- return LinkWithTo as LinkComponentType;
+ return SafeLink as LinkComponentType;
}
/**
- * Resolves the link component to use.
- *
- * Priority: `as` prop > `LinkProvider` context > native `<a>`.
- *
- * When the resolved component is a custom component (not the native `<a>`),
- * it is wrapped to receive both `href` and `to` props set to the same value.
- * This allows `to`-based routers (React Router, TanStack Router) to work
- * out of the box without a manual adapter.
- *
- * @param as - Per-component override. If provided, takes highest priority.
- * @returns The resolved link component (with `to` injection for custom components).
+ * Resolve `as`, then LinkProvider, then a native anchor. Both destination props
+ * are checked before rendering; accepted structured values retain identity.
+ * Custom components receive `to={href}` unless an explicit `to` is supplied.
*
* @example
* ```
- * function MyComponent({ as }: { as?: LinkComponentType }) {
- * const LinkComponent = useLinkComponent(as);
- * return <LinkComponent href="/foo">Click me</LinkComponent>;
- * }
+ * const LinkComponent = useLinkComponent(as);
+ * return <LinkComponent href="/docs">Documentation</LinkComponent>;
* ```
*/
-export function useLinkComponent(
- as?: LinkComponentType,
-): LinkComponentType {
+export function useLinkComponent(as?: LinkComponentType): LinkComponentType {
const ctx = use(LinkContext);
const resolved = as ?? ctx?.component ?? 'a';
-
- // Memoize the wrapper to maintain referential stability.
- // The wrapper is only created for custom components (not native <a>).
- return useMemo(() => {
- if (resolved === 'a') {
- return 'a';
- }
- return createLinkWithTo(resolved);
- }, [resolved]);
+ return useMemo(() => createSafeLink(resolved), [resolved]);
}
diff --git a/packages/core/src/List/ListItem.doc.mjs b/packages/core/src/List/ListItem.doc.mjs
index 67d863d6ce..21ade534d9 100644
--- a/packages/core/src/List/ListItem.doc.mjs
+++ b/packages/core/src/List/ListItem.doc.mjs
@@ -67,7 +67,7 @@ export const docs = {
{
name: 'href',
type: 'string',
- description: 'Link URL; enables the invisible anchor pattern.',
+ description: 'Link URL; enables the invisible anchor pattern. The destination follows the shared navigation rule described on the Link `href` prop.',
},
{
name: 'target',
@@ -174,7 +174,7 @@ export const docsDense = {
onClick: 'Click handler; enables invisible button pattern.',
interactiveRef:
'Ref to a nested control that owns the item\'s keyboard access/action; row delegates surface clicks to it (useClickableContainer), no invisible button/anchor, no second tab stop (WCAG 4.1.2). Mutually exclusive with onClick/href.',
- href: 'Link URL; enables invisible anchor pattern.',
+ href: 'Link URL; enables invisible anchor pattern. Follows the shared navigation rule (see Link href).',
target: 'Link target attribute, only when href provided. target="_blank" auto-adds noopener noreferrer.',
rel: 'Link relationship tokens. noopener noreferrer are merged for target="_blank".',
isDisabled: 'Disabled state; sets aria-disabled.',
diff --git a/packages/core/src/Markdown/Markdown.doc.mjs b/packages/core/src/Markdown/Markdown.doc.mjs
index 7357f8eb71..47402e0ad5 100644
--- a/packages/core/src/Markdown/Markdown.doc.mjs
+++ b/packages/core/src/Markdown/Markdown.doc.mjs
@@ -112,7 +112,7 @@ export const docs = {
name: 'onLinkClick',
type: '(href: string, event: MouseEvent) => void | false',
description:
- 'Handler for link clicks. Return false to prevent the default navigation behavior.',
+ 'Handler for link clicks. Return false to prevent the default navigation behavior. Link destinations in the markdown follow the shared navigation rule described on the Link `href` prop: a blocked destination renders as plain text and never reaches this handler or a custom link renderer. Image URLs use a separate, stricter policy (every data: URL is rejected).',
},
{
name: 'sources',
@@ -859,7 +859,7 @@ export const docsDense = {
isStreaming:
'Incremental parse + fade-in for streamed chunks. Default: false.',
onLinkClick:
- '(href, event) => void|false. Return false prevents navigation.',
+ '(href, event) => void|false. Return false prevents navigation. Link destinations follow the shared navigation rule (see Link href); blocked ones render as text. Image URLs: separate stricter policy.',
sources:
'Record<string, MarkdownSource>. Citation sources by ID. [id]/【id】 markers render as chips.',
citationStyle:
diff --git a/packages/core/src/Markdown/Markdown.renderBoundary.test.tsx b/packages/core/src/Markdown/Markdown.renderBoundary.test.tsx
new file mode 100644
index 0000000000..56bd2f780c
--- /dev/null
+++ b/packages/core/src/Markdown/Markdown.renderBoundary.test.tsx
@@ -0,0 +1,72 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Markdown.renderBoundary.test.tsx
+ * @input Uses vitest, @testing-library/react, Markdown with a mocked parser
+ * @output Tests for the render-side navigation check in Markdown
+ * @position Testing; the parser already rejects blocked destinations, so
+ * these tests bypass it and hand the renderer a pre-parsed link node.
+ * That pins the render boundary on its own: it must apply the shared
+ * navigation rule (utils/safeUrl.ts) even when a link node arrives with a
+ * destination the parser never saw.
+ */
+
+import {afterEach, describe, expect, it, vi} from 'vitest';
+import {cleanup, render} from '@testing-library/react';
+import {Markdown} from './Markdown';
+import type * as Parser from './parser';
+import type {MarkdownAstBlockContent} from './ast';
+
+const parsed: {blocks: MarkdownAstBlockContent[]} = {blocks: []};
+
+vi.mock('./parser', async importOriginal => {
+ const actual = await importOriginal<typeof Parser>();
+ return {
+ ...actual,
+ parseMarkdownAst: () => ({type: 'root', children: parsed.blocks}),
+ };
+});
+
+function linkParagraph(url: string): MarkdownAstBlockContent[] {
+ return [
+ {
+ type: 'paragraph',
+ children: [{type: 'link', url, children: [{type: 'text', value: 'go'}]}],
+ },
+ ];
+}
+
+afterEach(() => {
+ cleanup();
+});
+
+describe('Markdown render boundary — link destinations', () => {
+ it('renders an accepted pre-parsed destination as a link', () => {
+ parsed.blocks = linkParagraph('data:image/png;base64,iVBORw0KGgo=');
+ const {container} = render(<Markdown>{'ignored'}</Markdown>);
+ expect(container.querySelector('a')?.getAttribute('href')).toBe(
+ 'data:image/png;base64,iVBORw0KGgo=',
+ );
+ });
+
+ it.each([
+ 'javascript:alert(1)',
+ 'vbscript:MsgBox(1)',
+ 'data:text/html,<script>alert(1)</script>',
+ 'java\nscript:alert(1)',
+ ])('renders a blocked pre-parsed destination %s as text', href => {
+ parsed.blocks = linkParagraph(href);
+ const {container} = render(<Markdown>{'ignored'}</Markdown>);
+ expect(container.querySelector('a')).toBeNull();
+ expect(container.textContent).toContain('go');
+ });
+
+ it('does not hand a blocked destination to a custom link renderer', () => {
+ parsed.blocks = linkParagraph('javascript:alert(1)');
+ const link = vi.fn(({children}: {href: string; children?: unknown}) => (
+ <a data-custom>{children as never}</a>
+ ));
+ render(<Markdown components={{link}}>{'ignored'}</Markdown>);
+ expect(link).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/core/src/Markdown/Markdown.spec.md b/packages/core/src/Markdown/Markdown.spec.md
index cc2fd2bb2d..3a83747366 100644
--- a/packages/core/src/Markdown/Markdown.spec.md
+++ b/packages/core/src/Markdown/Markdown.spec.md
@@ -13,6 +13,7 @@ review_triggers: [api, theming]
verified_by:
[
packages/core/src/Markdown/Markdown.test.tsx,
+ packages/core/src/Markdown/Markdown.renderBoundary.test.tsx,
packages/core/src/Markdown/Markdown.public.test.ts,
packages/core/src/Markdown/parser.test.ts,
packages/core/src/Markdown/incremental.test.ts,
@@ -316,7 +317,9 @@ and this change preserves the existing spelling exactly.
current with the implementation.
- `family:navigation-destinations` owns the shared accept/block result for parsed
links and every Astryx-owned navigation sink. `spec:AST-005/DEC-1` requires
- Markdown navigation to remain conformant with Core link plumbing.
+ Markdown parsing and link rendering to preserve the same normalized navigation
+ decision as other Core links. Rejected links remain inert and do not reach a
+ custom link renderer; accepted links retain their ordinary behavior.
- `spec:AST-005/DEC-2` keeps embedded-resource policy separate. Markdown may
reject a broader set of image/resource URLs without narrowing the shared
navigation contract.
@@ -332,20 +335,21 @@ and this change preserves the existing spelling exactly.
## Verification map
-| Contract | Verification | Representative states | Failure signal |
-| ---------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
-| FR1–FR5 | `Markdown.test.tsx`, theme-target tests, and `scripts/check-knowledge.mjs` | Default block/inline output and all current targets | Existing DOM, target, spacing, or renderer behavior changes. |
-| FR6–FR10 | `parser.test.ts` and `Markdown.test.tsx` | Opt-out, inline/display math, escapes, currency, code, links, plugins | A delimiter is claimed without opt-in, TeX is formatted as Markdown, or opaque contexts leak. |
-| FR11 | `incremental.test.ts` and `Markdown.test.tsx` | Every-character top-level/list/task-list/blockquote splits, CRLF, source ranges | Streaming diverges from a full parse, shows partial syntax, mistakes a nested closer for an opener, or crosses a closed container. |
-| FR12–FR16 | plugin, transform, adapter, performance, and Outline parser tests | omitted/empty lists, immutable transforms, invalid outputs, live updates, one compatible Remark plugin, duplicate headings | Empty behavior forks, input mutates, invalid structure escapes, transforms reparse, adapter loses content, budgets fail, or heading targets diverge. |
-| FR17–FR18 | container parse/validation, ownership, and dependency tests | leaf/container declarations, nested containers, foreign read/remove/mint/edit, unmet/misordered dependencies | Plugin-built parsed children, invalid content, lost fallback children, foreign mint/edit, or generic ownership codes. |
-| FR19 | diagnostic-channel tests in development and production | every phase, advisory reports, rate suppression, no handler, malformed list, duplicate Core, version skew | A silent production failure, document content in a diagnostic, or one entrypoint throwing where another recovers. |
-| FR20–FR22 | canonical/server imports, inference, streaming, preparation, theming tests | server imports, no explicit type args, chunk boundaries, recreated lists, themed/unthemed extensions | Client references, explicit-type workarounds, oscillation, per-render re-preparation, or unreachable opted-in output. |
-| FR23 | parser, renderer, nesting, and public option tests | task-only, plain-only, and mixed ordered/unordered lists at top level and nested; autolink omitted/enabled | A mixed list splits or loses order/state, a plain item becomes a checkbox, or `autolink: 'gfm'` changes non-autolink syntax. |
-| FR24 | `plugins/frontmatter.test.tsx`, Storybook, and server rendering | complete, malformed, non-leading, LF/CRLF, unfinished streaming, full plugin stack | Metadata syntax renders after completion, unfinished syntax leaks while streaming, typing is lost, or later plugins stop composing. |
-| FR25 | `parser.public.test.ts`, plugin SSR tests, and package export checks | server/RSC parsing with plugins, synchronous SSR, suspending renderer streaming boundary | A server import gains `use client`, plugin execution needs serialization, SSR loses fallback, or direct RSC rendering is misrepresented as supported. |
-| Public syntax/types | `Markdown.public.test.ts`, core typecheck, and `Markdown.doc.mjs` | Legacy exhaustive switches, math opt-ins, inferred extension-node unions | A released union widens, an enabled union loses nodes, or docs drift from declarations. |
-| Security/accessibility | `parser.test.ts`, `Markdown.test.tsx`, and renderer guidance | Inert expression strings and renderer-owned semantics | Astryx executes math as HTML or silently claims renderer-owned accessibility. |
+| Contract | Verification | Representative states | Failure signal |
+| ---------------------- | ----------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
+| FR1–FR5 | `Markdown.test.tsx`, theme-target tests, and `scripts/check-knowledge.mjs` | Default block/inline output and all current targets | Existing DOM, target, spacing, or renderer behavior changes. |
+| FR6–FR10 | `parser.test.ts` and `Markdown.test.tsx` | Opt-out, inline/display math, escapes, currency, code, links, plugins | A delimiter is claimed without opt-in, TeX is formatted as Markdown, or opaque contexts leak. |
+| FR11 | `incremental.test.ts` and `Markdown.test.tsx` | Every-character top-level/list/task-list/blockquote splits, CRLF, source ranges | Streaming diverges from a full parse, shows partial syntax, mistakes a nested closer for an opener, or crosses a closed container. |
+| FR12–FR16 | plugin, transform, adapter, performance, and Outline parser tests | omitted/empty lists, immutable transforms, invalid outputs, live updates, one compatible Remark plugin, duplicate headings | Empty behavior forks, input mutates, invalid structure escapes, transforms reparse, adapter loses content, budgets fail, or heading targets diverge. |
+| FR17–FR18 | container parse/validation, ownership, and dependency tests | leaf/container declarations, nested containers, foreign read/remove/mint/edit, unmet/misordered dependencies | Plugin-built parsed children, invalid content, lost fallback children, foreign mint/edit, or generic ownership codes. |
+| FR19 | diagnostic-channel tests in development and production | every phase, advisory reports, rate suppression, no handler, malformed list, duplicate Core, version skew | A silent production failure, document content in a diagnostic, or one entrypoint throwing where another recovers. |
+| FR20–FR22 | canonical/server imports, inference, streaming, preparation, theming tests | server imports, no explicit type args, chunk boundaries, recreated lists, themed/unthemed extensions | Client references, explicit-type workarounds, oscillation, per-render re-preparation, or unreachable opted-in output. |
+| FR23 | parser, renderer, nesting, and public option tests | task-only, plain-only, and mixed ordered/unordered lists at top level and nested; autolink omitted/enabled | A mixed list splits or loses order/state, a plain item becomes a checkbox, or `autolink: 'gfm'` changes non-autolink syntax. |
+| FR24 | `plugins/frontmatter.test.tsx`, Storybook, and server rendering | complete, malformed, non-leading, LF/CRLF, unfinished streaming, full plugin stack | Metadata syntax renders after completion, unfinished syntax leaks while streaming, typing is lost, or later plugins stop composing. |
+| FR25 | `parser.public.test.ts`, plugin SSR tests, and package export checks | server/RSC parsing with plugins, synchronous SSR, suspending renderer streaming boundary | A server import gains `use client`, plugin execution needs serialization, SSR loses fallback, or direct RSC rendering is misrepresented as supported. |
+| Public syntax/types | `Markdown.public.test.ts`, core typecheck, and `Markdown.doc.mjs` | Legacy exhaustive switches, math opt-ins, inferred extension-node unions | A released union widens, an enabled union loses nodes, or docs drift from declarations. |
+| Navigation contract | `parser.test.ts`, `Markdown.test.tsx`, and `Markdown.renderBoundary.test.tsx` | Parsed and rendered links, including transformed built-in links; accepted ordinary schemes; rejected destinations; links versus images | A blocked destination reaches navigation or a custom link renderer, or resource policy narrows accepted navigation. |
+| Security/accessibility | `parser.test.ts`, `Markdown.test.tsx`, and renderer guidance | Inert expression strings and renderer-owned semantics | Astryx executes math as HTML or silently claims renderer-owned accessibility. |
Focused tests continue to pin all nine current target names and default block
placement. Math intentionally adds no target and no default anatomy.
diff --git a/packages/core/src/Markdown/Markdown.test.tsx b/packages/core/src/Markdown/Markdown.test.tsx
index 98b9d2a8ff..e1cc5f8eea 100644
--- a/packages/core/src/Markdown/Markdown.test.tsx
+++ b/packages/core/src/Markdown/Markdown.test.tsx
@@ -636,6 +636,58 @@ describe('Markdown', () => {
expect(links[1].getAttribute('href')).toBe('/page');
});
+ describe('link destinations follow the shared navigation rule', () => {
+ // The same matrix Core's link plumbing and imperative navigation apply
+ // (utils/safeUrl.ts): only executable document schemes are blocked.
+ const blocked = [
+ 'javascript:alert(1)',
+ 'JaVaScRiPt:alert(1)',
+ 'vbscript:MsgBox(1)',
+ 'data:text/html,<script>alert(1)</script>',
+ 'java\nscript:alert(1)',
+ ];
+ const accepted = [
+ 'https://example.com',
+ '/page',
+ '#section',
+ '//example.com/x',
+ 'mailto:[email protected]',
+ 'tel:+15555550100',
+ 'data:image/png;base64,iVBORw0KGgo=',
+ ];
+
+ it.each(blocked)('renders %s as text, not a link', destination => {
+ const {container} = render(
+ <Markdown>{`[click](${destination})`}</Markdown>,
+ );
+ expect(container.querySelector('a')).toBeNull();
+ expect(container.textContent).toContain('click');
+ });
+
+ it.each(accepted)('renders %s as a link', destination => {
+ const {container} = render(
+ <Markdown>{`[click](${destination})`}</Markdown>,
+ );
+ const link = container.querySelector('a');
+ expect(link).not.toBeNull();
+ expect(link?.getAttribute('href')).toBe(destination);
+ });
+
+ it('a data:image link is navigation and is accepted, while a data:image image stays rejected by the resource policy', () => {
+ const {container} = render(
+ <Markdown>
+ {
+ '[view](data:image/png;base64,iVBORw0KGgo=)\n\n![pic](data:image/png;base64,iVBORw0KGgo=)'
+ }
+ </Markdown>,
+ );
+ expect(container.querySelector('a')?.getAttribute('href')).toBe(
+ 'data:image/png;base64,iVBORw0KGgo=',
+ );
+ expect(container.querySelector('img')).toBeNull();
+ });
+ });
+
it('preserves dollar-delimited text when no math renderer is supplied', () => {
const {container} = render(
<Markdown>{'Total $5 and formula $x_1 + *y*$.'}</Markdown>,
diff --git a/packages/core/src/Markdown/Markdown.tsx b/packages/core/src/Markdown/Markdown.tsx
index 45ec33b8bf..e208301ec8 100644
--- a/packages/core/src/Markdown/Markdown.tsx
+++ b/packages/core/src/Markdown/Markdown.tsx
@@ -76,7 +76,7 @@ import type {
MarkdownPluginEntry,
PreparedMarkdownPlugins,
} from './plugins/protocol';
-import {sanitizeMarkdownUrl} from './url';
+import {sanitizeMarkdownLinkUrl, sanitizeMarkdownUrl} from './url';
import {themeProps} from '../utils/themeProps';
import {useTranslator, type TranslatorFn} from '../i18n';
@@ -961,7 +961,7 @@ function renderInline(
return <MathComp key={index} value={node.value} display="inline" />;
}
case 'link': {
- const safeHref = sanitizeMarkdownUrl(node.url);
+ const safeHref = sanitizeMarkdownLinkUrl(node.url);
if (safeHref == null) {
// Unsafe URL — render as plain text
return (
diff --git a/packages/core/src/Markdown/parser.test.ts b/packages/core/src/Markdown/parser.test.ts
index 01ddda255c..bf390a15b0 100644
--- a/packages/core/src/Markdown/parser.test.ts
+++ b/packages/core/src/Markdown/parser.test.ts
@@ -165,6 +165,26 @@ describe('parseInline', () => {
}
});
+ it('decides link destinations with the shared navigation rule', () => {
+ const destinations: [string, boolean][] = [
+ ['https://example.com', true],
+ ['/page', true],
+ ['#section', true],
+ ['mailto:[email protected]', true],
+ ['tel:+1234567890', true],
+ ['custom:document', true],
+ ['data:image/png;base64,iVBORw0KGgo=', true],
+ ['javascript:alert(1)', false],
+ ['vbscript:MsgBox(1)', false],
+ ['data:text/html,<b>x</b>', false],
+ ['java\u0000script:alert(1)', false],
+ ];
+ for (const [destination, accepted] of destinations) {
+ const [node] = parseInline(`[t](${destination})`);
+ expect(node.type === 'link').toBe(accepted);
+ }
+ });
+
it('parses strikethrough', () => {
const result = parseInline('~~deleted~~');
expect(result[0].type).toBe('strikethrough');
diff --git a/packages/core/src/Markdown/url.ts b/packages/core/src/Markdown/url.ts
index 614dca042d..107f59a3c3 100644
--- a/packages/core/src/Markdown/url.ts
+++ b/packages/core/src/Markdown/url.ts
@@ -7,8 +7,8 @@
* @position Shared URL policy for parser, transforms, and renderer
*/
-const PARSER_DANGEROUS_URL_PATTERN =
- /^(?:javascript:|data:text\/html|vbscript:)/i;
+import {isSafeUrl, sanitizeUrl} from '../utils/safeUrl';
+
const RENDER_DANGEROUS_URL_PATTERN = /^(?:javascript:|data:|vbscript:)/i;
function normalizeMarkdownUrl(url: string): string {
@@ -19,7 +19,13 @@ function normalizeMarkdownUrl(url: string): string {
/** Preserve the released parser policy for no-plugin output compatibility. */
export function isSafeMarkdownParserUrl(url: string): boolean {
- return !PARSER_DANGEROUS_URL_PATTERN.test(normalizeMarkdownUrl(url));
+ return isSafeUrl(url);
+}
+
+/** Navigation and image rendering deliberately have different policies. */
+export function sanitizeMarkdownLinkUrl(url: string): string | null {
+ const normalized = sanitizeUrl(url);
+ return normalized === '' ? null : normalized;
}
export function sanitizeMarkdownUrl(url: string): string | null {
diff --git a/packages/core/src/Token/Token.doc.mjs b/packages/core/src/Token/Token.doc.mjs
index 54312903b8..c78a1fd96d 100644
--- a/packages/core/src/Token/Token.doc.mjs
+++ b/packages/core/src/Token/Token.doc.mjs
@@ -55,7 +55,7 @@ export const docs = {
name: 'href',
type: 'string',
description:
- 'Link URL. When provided, the token renders as an <a> element.',
+ 'Link URL. When provided, the token renders as an <a> element. The destination follows the shared navigation rule described on the Link `href` prop.',
},
{
name: 'description',
@@ -241,7 +241,7 @@ export const docsDense = {
isDisabled: 'Reduces opacity, blocks interactions.',
onRemove: 'Fired on remove button click. Renders X button when provided.',
onClick: 'Click handler. Renders <span> w/ invisible <button> inside for a11y.',
- href: 'Link URL. Renders as <a> element.',
+ href: 'Link URL. Renders as <a> element. Follows the shared navigation rule (see Link href).',
description: 'A11y description via aria-description on root.',
endContent: 'Content after label, before remove button.',
isLabelHidden: 'Visually hides label w/ screen-reader-only clip; stays accessible.',
diff --git a/packages/core/src/TopNav/TopNavMenu.doc.mjs b/packages/core/src/TopNav/TopNavMenu.doc.mjs
index 5ecce00219..558bad2f04 100644
--- a/packages/core/src/TopNav/TopNavMenu.doc.mjs
+++ b/packages/core/src/TopNav/TopNavMenu.doc.mjs
@@ -27,7 +27,7 @@ export const docs = {
{
name: 'items',
type: 'TopNavMenuItemData[]',
- description: 'Menu items to display in the hover popover.',
+ description: 'Menu items to display in the hover popover. Item href values follow the shared navigation rule described on Link; rejected destinations remain visible without navigation.',
required: true,
},
{
@@ -83,7 +83,7 @@ export const docsDense = {
description: 'Nav item w/ hover-triggered popover menu containing rich items w/ icon, title, optional description.',
propDescriptions: {
label: 'Trigger button visible label.',
- items: 'Menu items in hover popover.',
+ items: 'Menu items in hover popover. href follows the Link navigation rule; rejected destinations do not navigate.',
delay: 'Show delay ms on hover.',
hideDelay: 'Hide delay ms after mouse leaves.',
},
diff --git a/packages/core/src/TopNav/TopNavMenu.test.tsx b/packages/core/src/TopNav/TopNavMenu.test.tsx
index f84af66003..7a87f89e72 100644
--- a/packages/core/src/TopNav/TopNavMenu.test.tsx
+++ b/packages/core/src/TopNav/TopNavMenu.test.tsx
@@ -31,6 +31,36 @@ const mockItems = [
];
describe('TopNavMenu', () => {
+ it.each([
+ 'javascript:alert(1)',
+ 'vbscript:MsgBox(1)',
+ 'data:text/html,<b>x</b>',
+ ])('does not expose rejected menu destination %s', href => {
+ const onClick = vi.fn();
+ render(
+ <TopNavMenu
+ label="Menu"
+ items={[{title: 'Destination', href, onClick}]}
+ />,
+ );
+ const item = screen.getByRole('menuitem', {hidden: true});
+ expect(item).not.toHaveAttribute('href');
+ fireEvent.click(item);
+ expect(onClick).toHaveBeenCalledOnce();
+ });
+
+ it('preserves an accepted native menu destination', () => {
+ render(
+ <TopNavMenu
+ label="Menu"
+ items={[{title: 'Destination', href: '/docs'}]}
+ />,
+ );
+ expect(screen.getByRole('menuitem', {hidden: true})).toHaveAttribute(
+ 'href',
+ '/docs',
+ );
+ });
it('renders the trigger button with label', () => {
render(<TopNavMenu label="Products" items={mockItems} />);
expect(screen.getByRole('button', {name: 'Products'})).toBeInTheDocument();
diff --git a/packages/core/src/TopNav/TopNavMenu.tsx b/packages/core/src/TopNav/TopNavMenu.tsx
index 2f5febe54b..906901814f 100644
--- a/packages/core/src/TopNav/TopNavMenu.tsx
+++ b/packages/core/src/TopNav/TopNavMenu.tsx
@@ -5,7 +5,7 @@
/**
* @file TopNavMenu.tsx
* @input Uses React, StyleX, usePopover, useMenuHover, useListFocus,
- * useTypeahead, TopNavItem tokens
+ * useTypeahead, TopNavItem tokens, and the shared navigation policy
* @output Exports TopNavMenu component and related types
* @position Navigation item with hover-triggered overflow menu for TopNav
*
@@ -37,6 +37,7 @@ import {useTopNavSlot} from './TopNavContext';
import {useTopNavRenderMode} from './TopNavRenderContext';
import {useAppShellMobile} from '../AppShell/AppShellMobileContext';
import {useLinkComponent} from '../Link/useLinkComponent';
+import {isSafeUrl} from '../utils/safeUrl';
import {themeProps} from '../utils/themeProps';
import {focusOutlineProps} from '../utils/focusOutline.stylex';
import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';
@@ -575,7 +576,11 @@ export function TopNavMenu({
// Single tab stop: useListFocus owns the roving tabindex and
// promotes exactly one item to 0.
tabIndex={-1}
- href={item.href}
+ href={
+ item.href != null && isSafeUrl(item.href)
+ ? item.href
+ : undefined
+ }
onClick={item.onClick}
{...focusOutlineProps.focusVisible(styles.menuItem)}>
<div {...stylex.props(styles.menuItemIcon)}>{item.icon}</div>
diff --git a/packages/core/src/hooks/useClickableContainer.test.tsx b/packages/core/src/hooks/useClickableContainer.test.tsx
new file mode 100644
index 0000000000..81dcede631
--- /dev/null
+++ b/packages/core/src/hooks/useClickableContainer.test.tsx
@@ -0,0 +1,236 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useClickableContainer.test.tsx
+ * @input Uses vitest, @testing-library/react, useClickableContainer
+ * @output Unit tests for the hook's navigation paths
+ * @position Testing; pins the shared navigation-destination rule on every
+ * activation method the hook owns — plain click (location.href), new tab
+ * (target="_blank"), Cmd/Ctrl-click, middle-click, and the delegated click
+ * on the interactive ref. None of these pass through React DOM's own href
+ * vetting, so each one has a positive and a blocked case here.
+ */
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {useRef} from 'react';
+import {fireEvent, render, screen} from '@testing-library/react';
+import {useClickableContainer} from './useClickableContainer';
+
+// The scheme the rule exists to stop (kept in consts so the JSX below stays
+// lint-clean — the tests are ABOUT these URLs never navigating).
+const scriptUrl = 'javascript:alert(1)';
+// The same scheme hidden behind a control character a browser ignores.
+const hiddenScriptUrl = 'java\nscript:alert(1)';
+
+function Card({href, target}: {href: string; target?: string}) {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const {onClick, onMouseUp} = useClickableContainer({
+ containerRef,
+ href,
+ target,
+ });
+ return (
+ <div
+ ref={containerRef}
+ data-testid="card"
+ onClick={onClick}
+ onMouseUp={onMouseUp}>
+ content
+ </div>
+ );
+}
+
+/**
+ * Card that delegates plain clicks to an inner link (the ClickableCard /
+ * Item shape). The inner anchor's own click is spied on so the test observes
+ * whether the hook activated it.
+ */
+function DelegatingCard({
+ href,
+ onAnchorClick,
+}: {
+ href: string;
+ onAnchorClick: () => void;
+}) {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const interactiveRef = useRef<HTMLAnchorElement>(null);
+ const {onClick, onMouseUp} = useClickableContainer({
+ containerRef,
+ interactiveRef,
+ href,
+ });
+ return (
+ <div
+ ref={containerRef}
+ data-testid="card"
+ onClick={onClick}
+ onMouseUp={onMouseUp}>
+ content
+ <a
+ ref={interactiveRef}
+ // The anchor is the delegate, not the subject: the tests below use a
+ // fixed inert href here so that only the hook's decision is observed.
+ href="#inner"
+ data-testid="inner-link"
+ onClick={e => {
+ e.preventDefault();
+ onAnchorClick();
+ }}>
+ inner
+ </a>
+ </div>
+ );
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+describe('useClickableContainer navigation — new tab (target="_blank")', () => {
+ it('opens ordinary hrefs in a new tab', () => {
+ const open = vi.spyOn(window, 'open').mockImplementation(() => null);
+ render(<Card href="https://example.com/docs" target="_blank" />);
+ fireEvent.click(screen.getByTestId('card'));
+ expect(open).toHaveBeenCalledWith(
+ 'https://example.com/docs',
+ '_blank',
+ 'noopener',
+ );
+ });
+
+ it('does not open a script-scheme href in a new tab', () => {
+ const open = vi.spyOn(window, 'open').mockImplementation(() => null);
+ // eslint-disable-next-line @eslint-react/dom-no-script-url -- the test proves this URL never navigates
+ render(<Card href={scriptUrl} target="_blank" />);
+ fireEvent.click(screen.getByTestId('card'));
+ expect(open).not.toHaveBeenCalled();
+ });
+});
+
+describe('useClickableContainer navigation — Cmd/Ctrl-click', () => {
+ it('opens ordinary hrefs in a new tab on Cmd-click', () => {
+ const open = vi.spyOn(window, 'open').mockImplementation(() => null);
+ render(<Card href="/docs" />);
+ fireEvent.click(screen.getByTestId('card'), {metaKey: true});
+ expect(open).toHaveBeenCalledWith('/docs', '_blank', 'noopener');
+ });
+
+ it('opens ordinary hrefs in a new tab on Ctrl-click', () => {
+ const open = vi.spyOn(window, 'open').mockImplementation(() => null);
+ render(<Card href="/docs" />);
+ fireEvent.click(screen.getByTestId('card'), {ctrlKey: true});
+ expect(open).toHaveBeenCalledWith('/docs', '_blank', 'noopener');
+ });
+
+ it('does not open a script-scheme href on Cmd-click', () => {
+ const open = vi.spyOn(window, 'open').mockImplementation(() => null);
+ // eslint-disable-next-line @eslint-react/dom-no-script-url -- the test proves this URL never navigates
+ render(<Card href={scriptUrl} />);
+ fireEvent.click(screen.getByTestId('card'), {metaKey: true});
+ expect(open).not.toHaveBeenCalled();
+ });
+
+ it('does not open a script-scheme href on Ctrl-click', () => {
+ const open = vi.spyOn(window, 'open').mockImplementation(() => null);
+ // eslint-disable-next-line @eslint-react/dom-no-script-url -- the test proves this URL never navigates
+ render(<Card href={scriptUrl} />);
+ fireEvent.click(screen.getByTestId('card'), {ctrlKey: true});
+ expect(open).not.toHaveBeenCalled();
+ });
+});
+
+describe('useClickableContainer navigation — middle-click', () => {
+ it('opens ordinary hrefs on middle-click', () => {
+ const open = vi.spyOn(window, 'open').mockImplementation(() => null);
+ render(<Card href="/docs" />);
+ fireEvent.mouseUp(screen.getByTestId('card'), {button: 1});
+ expect(open).toHaveBeenCalledWith('/docs', '_blank', 'noopener');
+ });
+
+ it('does not open a script-scheme href on middle-click', () => {
+ const open = vi.spyOn(window, 'open').mockImplementation(() => null);
+ // eslint-disable-next-line @eslint-react/dom-no-script-url -- the test proves this URL never navigates
+ render(<Card href={scriptUrl} />);
+ fireEvent.mouseUp(screen.getByTestId('card'), {button: 1});
+ expect(open).not.toHaveBeenCalled();
+ });
+});
+
+describe('useClickableContainer navigation — plain click (location.href)', () => {
+ // jsdom does not navigate, so assigning `location.href` is a no-op there
+ // and would let a missing guard pass unnoticed. Stand in a plain object so
+ // the assignment is observable.
+ let location: {href: string};
+
+ beforeEach(() => {
+ location = {href: 'https://app.example/start'};
+ vi.stubGlobal('location', location);
+ });
+
+ it('assigns ordinary hrefs to location', () => {
+ render(<Card href="/docs" />);
+ fireEvent.click(screen.getByTestId('card'));
+ expect(location.href).toBe('/docs');
+ });
+
+ it('does not assign a script-scheme href to location', () => {
+ // eslint-disable-next-line @eslint-react/dom-no-script-url -- the test proves this URL never navigates
+ render(<Card href={scriptUrl} />);
+ fireEvent.click(screen.getByTestId('card'));
+ expect(location.href).toBe('https://app.example/start');
+ });
+
+ it('does not assign a control-character-hidden script scheme to location', () => {
+ // eslint-disable-next-line @eslint-react/dom-no-script-url -- the test proves this URL never navigates
+ render(<Card href={hiddenScriptUrl} />);
+ fireEvent.click(screen.getByTestId('card'));
+ expect(location.href).toBe('https://app.example/start');
+ });
+});
+
+describe('useClickableContainer navigation — delegated interactive ref', () => {
+ it('delegates ordinary hrefs to the inner link', () => {
+ const onAnchorClick = vi.fn();
+ render(<DelegatingCard href="/docs" onAnchorClick={onAnchorClick} />);
+ fireEvent.click(screen.getByTestId('card'));
+ expect(onAnchorClick).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not delegate a script-scheme href to the inner link', () => {
+ const onAnchorClick = vi.fn();
+ // eslint-disable-next-line @eslint-react/dom-no-script-url -- the test proves this URL never navigates
+ render(<DelegatingCard href={scriptUrl} onAnchorClick={onAnchorClick} />);
+ fireEvent.click(screen.getByTestId('card'));
+ expect(onAnchorClick).not.toHaveBeenCalled();
+ });
+
+ it('a click on the inner link itself is left to the link', () => {
+ const onAnchorClick = vi.fn();
+ render(<DelegatingCard href="/docs" onAnchorClick={onAnchorClick} />);
+ fireEvent.click(screen.getByTestId('inner-link'));
+ // The anchor's own handler ran once; the hook did not proxy a second one.
+ expect(onAnchorClick).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('useClickableContainer navigation — blocked href keeps the rest', () => {
+ it('still fires the onClick handler for a blocked href', () => {
+ const onClick = vi.fn();
+ const open = vi.spyOn(window, 'open').mockImplementation(() => null);
+ function Surface() {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const handlers = useClickableContainer({
+ containerRef,
+ href: scriptUrl,
+ target: '_blank',
+ onClick,
+ });
+ return <div ref={containerRef} data-testid="card" {...handlers} />;
+ }
+ render(<Surface />);
+ fireEvent.click(screen.getByTestId('card'));
+ expect(onClick).toHaveBeenCalledTimes(1);
+ expect(open).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/core/src/hooks/useClickableContainer.ts b/packages/core/src/hooks/useClickableContainer.ts
index 4084d508a5..7e5071133a 100644
--- a/packages/core/src/hooks/useClickableContainer.ts
+++ b/packages/core/src/hooks/useClickableContainer.ts
@@ -11,11 +11,17 @@
* Solves the "nested interactive elements" problem: when a card is clickable
* but contains buttons/links, clicking those should NOT trigger the card's action.
*
+ * Every navigation exit here (window.open, location.href, and the delegated
+ * click on the interactive ref) runs after the shared navigation-destination
+ * rule in utils/safeUrl.ts; a blocked href does not navigate by any
+ * activation method.
+ *
* SYNC: When modified, update:
* - /packages/core/src/hooks/index.ts (export)
*/
import {useCallback, useEffect, type RefObject, type MouseEvent} from 'react';
+import {isSafeUrl} from '../utils/safeUrl';
/**
* Canonical list of interactive element selectors — native controls plus
@@ -89,7 +95,11 @@ export interface UseClickableContainerOptions {
interactiveRef?: RefObject<HTMLElement | null>;
/** Click handler */
onClick?: (event: MouseEvent<HTMLElement>) => void;
- /** Navigation URL — when provided, clicking the container navigates */
+ /**
+ * Navigation URL — when provided, clicking the container navigates. Checked
+ * with the shared navigation rule (utils/safeUrl.ts) before any activation
+ * method (plain, new-tab, Cmd/Ctrl-click, middle-click, delegated click).
+ */
href?: string;
/** Link target */
target?: string;
@@ -180,8 +190,12 @@ export function useClickableContainer({
return;
}
- // Navigate if href is provided
- if (href != null) {
+ // Navigate if href is provided. React DOM vets the hrefs it writes as
+ // attributes; nothing below passes through React, so the shared
+ // navigation rule decides once, before target, modifier key, or the
+ // delegated anchor can select a sink. A blocked href simply does not
+ // navigate — the click handler above still ran.
+ if (href != null && isSafeUrl(href)) {
const shouldOpenNewTab =
target === '_blank' || event.ctrlKey || event.metaKey;
if (shouldOpenNewTab) {
@@ -230,11 +244,13 @@ export function useClickableContainer({
return;
}
- // Middle-click on href opens in new tab
+ // Middle-click on href opens in new tab (same scheme rule as onClick —
+ // this navigation never passes through React either).
const isMiddleClick = event.button === 1;
if (
isMiddleClick &&
href != null &&
+ isSafeUrl(href) &&
(eventTarget === event.currentTarget ||
!hasInteractiveAncestor(eventTarget, containerEl))
) {
diff --git a/packages/core/src/utils/safeUrl.test.ts b/packages/core/src/utils/safeUrl.test.ts
new file mode 100644
index 0000000000..b8bc767912
--- /dev/null
+++ b/packages/core/src/utils/safeUrl.test.ts
@@ -0,0 +1,88 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+import {isSafeDestination, isSafeUrl, sanitizeUrl} from './safeUrl';
+
+// Expectations come from the navigation contract, not another policy helper.
+const accepted = [
+ 'https://example.com/a?b=c#d',
+ 'http://example.com',
+ '//example.com/protocol-relative',
+ '/relative/path',
+ 'relative/path',
+ '#fragment',
+ 'mailto:[email protected]',
+ 'tel:+1234567890',
+ 'custom:open/document',
+ 'data:image/png;base64,iVBORw0KGgo=',
+ 'data:text/plain,download',
+];
+const rejected = [
+ 'javascript:alert(1)',
+ 'JaVaScRiPt:alert(1)',
+ ' javascript:alert(1)',
+ 'vbscript:MsgBox(1)',
+ 'data:text/html,<script>alert(1)</script>',
+ 'DATA:TEXT/HTML;base64,PHNjcmlwdD4=',
+ 'java\tscript:alert(1)',
+ 'java\nscript:alert(1)',
+ '\x00javascript:alert(1)',
+ 'java\x7fscript:alert(1)',
+];
+
+describe('navigation strings', () => {
+ it.each(accepted)('accepts %s', url => {
+ expect(isSafeUrl(url)).toBe(true);
+ expect(isSafeDestination(url)).toBe(true);
+ expect(sanitizeUrl(url)).toBe(url);
+ });
+ it.each(rejected)('rejects %s', url => {
+ expect(isSafeUrl(url)).toBe(false);
+ expect(isSafeDestination(url)).toBe(false);
+ expect(sanitizeUrl(url)).toBeNull();
+ });
+ it('normalizes accepted strings only when requested', () => {
+ expect(sanitizeUrl(' /docs\n')).toBe('/docs');
+ expect(sanitizeUrl('/do\x00cs')).toBe('/docs');
+ });
+});
+
+describe('structured destinations', () => {
+ it.each([
+ {pathname: '/docs', search: '?q=1', hash: '#a'},
+ {href: 'https://example.com'},
+ {protocol: 'https:', hostname: 'example.com', pathname: '/docs'},
+ {protocol: 'custom', pathname: 'document'},
+ {protocol: 'mailto:', pathname: '[email protected]'},
+ {protocol: 'data:', pathname: 'image/png;base64,aA=='},
+ {search: '?page=2'},
+ {hash: '#section'},
+ {},
+ new URL('https://example.com/docs'),
+ undefined,
+ null,
+ ])('accepts supported destination %j', destination => {
+ expect(isSafeDestination(destination)).toBe(true);
+ });
+ it.each([
+ {pathname: 'javascript:alert(1)'},
+ {pathname: 'java\x00script:alert(1)'},
+ {href: 'vbscript:MsgBox(1)'},
+ {pathname: '/ok', href: 'javascript:1'},
+ {protocol: 'javascript:', pathname: 'alert(1)'},
+ {protocol: 'javascript', pathname: 'alert(1)'},
+ {protocol: ' JaVa\tsCrIpT ', pathname: 'alert(1)'},
+ {protocol: 'vbscript', pathname: 'MsgBox(1)'},
+ {protocol: 'data:', pathname: 'text/html,<b>x</b>'},
+ {protocol: 'data', pathname: 'TEXT/HTML;base64,PGI+eDwvYj4='},
+ {protocol: 'data:', host: 'text/', pathname: 'html,<b>x</b>'},
+ {protocol: 'data:', hostname: 'text/html,<b>x</b>'},
+ {href: '/safe', protocol: 'javascript:'},
+ new URL('javascript:alert(1)'),
+ {pathname: 42},
+ {protocol: {toString: (): string => 'javascript:'}},
+ 3,
+ ])('rejects blocked or unsupported destination %j', destination => {
+ expect(isSafeDestination(destination)).toBe(false);
+ });
+});
diff --git a/packages/core/src/utils/safeUrl.ts b/packages/core/src/utils/safeUrl.ts
new file mode 100644
index 0000000000..3c6ea7d5e7
--- /dev/null
+++ b/packages/core/src/utils/safeUrl.ts
@@ -0,0 +1,85 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file safeUrl.ts
+ * @input Navigation strings or supported structured router destinations
+ * @output The shared blocked-scheme decision, without rewriting accepted inputs
+ * @position Core navigation policy; embedded-resource policy is separate
+ */
+
+function normalizeUrl(url: string): string {
+ // eslint-disable-next-line no-control-regex -- inspect schemes without browser-ignored controls
+ return url.replace(/[\x00-\x1f\x7f]/g, '').trim();
+}
+
+/** Return a normalized navigation URL, or null for a blocked scheme. */
+export function sanitizeUrl(url: string): string | null {
+ const normalized = normalizeUrl(url);
+ const lower = normalized.toLowerCase();
+ if (
+ lower.startsWith('javascript:') ||
+ lower.startsWith('vbscript:') ||
+ lower.startsWith('data:text/html')
+ ) {
+ return null;
+ }
+ return normalized;
+}
+
+/** Inspect a navigation string without changing the value used by its sink. */
+export function isSafeUrl(url: string): boolean {
+ return sanitizeUrl(url) !== null;
+}
+
+/**
+ * Inspect React Router paths, Next.js URL objects, and URL instances without
+ * serializing or replacing the object handed to the router. Search/query/hash
+ * are route-relative data, not schemes. Absent destinations remain absent.
+ */
+export function isSafeDestination(destination: unknown): boolean {
+ if (destination == null) {
+ return true;
+ }
+ if (typeof destination === 'string') {
+ return isSafeUrl(destination);
+ }
+ if (typeof destination !== 'object') {
+ return false;
+ }
+
+ const {pathname, href, protocol, host, hostname} = destination as {
+ pathname?: unknown;
+ href?: unknown;
+ protocol?: unknown;
+ host?: unknown;
+ hostname?: unknown;
+ };
+ for (const field of [pathname, href, protocol, host, hostname]) {
+ if (field != null && typeof field !== 'string') {
+ return false;
+ }
+ }
+ if (typeof pathname === 'string' && !isSafeUrl(pathname)) {
+ return false;
+ }
+ if (typeof href === 'string' && !isSafeUrl(href)) {
+ return false;
+ }
+ if (typeof protocol === 'string' && protocol !== '') {
+ // URL-object formatters accept a protocol with or without its colon and
+ // can assemble a data media type from the host and pathname fields.
+ const normalizedProtocol = normalizeUrl(protocol);
+ const prefix = normalizedProtocol.endsWith(':')
+ ? normalizedProtocol
+ : `${normalizedProtocol}:`;
+ if (!isSafeUrl(prefix)) {
+ return false;
+ }
+ const body = (host || hostname || '') as string;
+ const path = typeof pathname === 'string' ? pathname : '';
+ if (!isSafeUrl(`${prefix}${body}${path}`)) {
+ return false;
+ }
+ }
+ return true;
+}