Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,7 @@ To disable a rule for an entire `.gjs`/`.gts` file, use a regular ESLint file-le
| [template-no-heading-inside-button](docs/rules/template-no-heading-inside-button.md) | disallow heading elements inside button elements | 📋 | | |
| [template-no-invalid-aria-attributes](docs/rules/template-no-invalid-aria-attributes.md) | disallow invalid aria-* attributes | 📋 | | |
| [template-no-invalid-interactive](docs/rules/template-no-invalid-interactive.md) | disallow non-interactive elements with interactive handlers | 📋 | | |
| [template-no-invalid-link-href](docs/rules/template-no-invalid-link-href.md) | disallow invalid href values on `<a>` and `<area>` elements | | | |
| [template-no-invalid-link-text](docs/rules/template-no-invalid-link-text.md) | disallow invalid or uninformative link text content | 📋 | | |
| [template-no-invalid-link-title](docs/rules/template-no-invalid-link-title.md) | disallow invalid title attributes on link elements | 📋 | | |
| [template-no-invalid-role](docs/rules/template-no-invalid-role.md) | disallow invalid ARIA roles | 📋 | | |
Expand Down
51 changes: 51 additions & 0 deletions docs/rules/template-no-invalid-link-href.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# ember/template-no-invalid-link-href

<!-- end auto-generated rule header -->

Disallow link elements — `<a>` and `<area>` — whose `href` value is a commonly-misused placeholder (e.g. `href="#"`, `href=""`, `href="javascript:..."`). Both carry URL semantics per the HTML spec ([the `<a>` element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-a-element), [the `<area>` element](https://html.spec.whatwg.org/multipage/image-maps.html#the-area-element)), so the same validity rules apply on each.

This rule is **pragmatic accessibility/UX guidance, not spec enforcement.** Values like `href="#"` and `href="javascript:void(0)"` are technically valid URLs per the [HTML spec](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-a-element); the rule flags them because they are widely-recognized anti-patterns for faking a clickable anchor:

- Breaks expected keyboard behavior (anchors should navigate; buttons should act)
- The `javascript:` pseudo-protocol is [called out as an anti-pattern by MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/a#javascript_pseudo-protocol)
- Leaves assistive tech announcing a link that doesn't navigate

If a click handler is what you want, use a `<button>`. If you want a genuine fragment link, use `href="#section-id"`.

Complements [`template-link-href-attributes`](./template-link-href-attributes.md), which handles the **missing** href case. This rule validates the href **value**.

## Examples

This rule **forbids** the following:

```gjs
<template>
<a href="#">Click</a>
<a href="#!">Click</a>
<a href="">Click</a>
<a href>Click</a>
<a href="javascript:void(0)">Click</a>
<a href="JavaScript:alert(1)">Execute</a>
</template>
```

This rule **allows** the following:

```gjs
<template>
<a href="/x">Link</a>
<a href="https://example.com">Link</a>
<a href="#section">Fragment link</a>
<a href="mailto:[email protected]">Email</a>
<a href={{this.url}}>Dynamic</a>
</template>
```

Mustache hrefs whose value is a **static literal** (string, number, or boolean) are validated — the rule unwraps them to their static value via `getStaticAttrValue`. Only **truly dynamic** mustaches (PathExpressions, helpers with arguments, or concat statements that include a dynamic part) are skipped, because we can't statically determine what they will resolve to at runtime.

## References

- [HTML Living Standard — the `<a>` element](https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-a-element)
- [MDN — `<a>` — javascript: pseudo-protocol](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/a#javascript_pseudo-protocol)
- [`anchor-is-valid` — eslint-plugin-jsx-a11y](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/main/docs/rules/anchor-is-valid.md)
- [`anchor-is-valid` — eslint-plugin-lit-a11y](https://github.com/open-wc/open-wc/blob/main/packages/eslint-plugin-lit-a11y/docs/rules/anchor-is-valid.md)
Binary file added lib/rules/template-no-invalid-link-href.js
Binary file not shown.
66 changes: 66 additions & 0 deletions lib/utils/static-attr-value.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
'use strict';

/**
* Return the statically-known string value of a Glimmer attribute value node,
* or `undefined` when the value is dynamic (cannot be resolved at lint time).
*
* Unwraps:
* - GlimmerTextNode → chars
* - GlimmerMustacheStatement with a literal path (boolean/string/number) → stringified value
* - GlimmerConcatStatement whose parts are all statically resolvable → joined string
*
* A missing/undefined value (valueless attribute, e.g. `<input disabled>`)
* returns the empty string. Pass `attr.value` — not the attribute itself.
*/
function getStaticAttrValue(value) {
if (value === null || value === undefined) {
return '';
}
if (value.type === 'GlimmerTextNode') {
return value.chars;
}
if (value.type === 'GlimmerMustacheStatement') {
return extractLiteral(value.path);
}
if (value.type === 'GlimmerConcatStatement') {
if (!Array.isArray(value.parts)) {
return undefined;
}
let out = '';
for (const part of value.parts) {
if (part.type === 'GlimmerTextNode') {
out += part.chars;
continue;
}
if (part.type === 'GlimmerMustacheStatement') {
const literal = extractLiteral(part.path);
if (literal === undefined) {
return undefined;
}
out += literal;
continue;
}
return undefined;
}
return out;
}
return undefined;
}

function extractLiteral(path) {
if (!path) {
return undefined;
}
if (path.type === 'GlimmerBooleanLiteral') {
return path.value ? 'true' : 'false';
}
if (path.type === 'GlimmerStringLiteral') {
return path.value;
}
if (path.type === 'GlimmerNumberLiteral') {
return String(path.value);
}
return undefined;
}

module.exports = { getStaticAttrValue };
154 changes: 154 additions & 0 deletions tests/lib/rules/template-no-invalid-link-href.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
'use strict';

const rule = require('../../../lib/rules/template-no-invalid-link-href');
const RuleTester = require('eslint').RuleTester;

const ruleTester = new RuleTester({
parser: require.resolve('ember-eslint-parser'),
parserOptions: { ecmaVersion: 2022, sourceType: 'module' },
});

ruleTester.run('template-no-invalid-link-href', rule, {
valid: [
// Valid navigable hrefs.
'<template><a href="/x">Link</a></template>',
'<template><a href="https://example.com">Link</a></template>',
'<template><a href="#section">Link</a></template>',
'<template><a href="mailto:[email protected]">Email</a></template>',
'<template><a href="tel:+47123">Phone</a></template>',

// Dynamic href — rule can't statically validate, skips.
'<template><a href={{this.url}}>Link</a></template>',
'<template><a href="{{this.prefix}}/{{this.slug}}">Link</a></template>',

Comment thread
johanrd marked this conversation as resolved.
Comment thread
johanrd marked this conversation as resolved.
// No href at all — handled by template-link-href-attributes, not this rule.
'<template><a>Not a link</a></template>',

// Non-anchor elements are not in scope.
'<template><button>Click me</button></template>',
'<template><div href="#">Not an anchor</div></template>',

// <area> is in scope — same href semantics as <a>. Valid values pass.
'<template><map name="m"><area href="/region-a" shape="rect" coords="0,0,10,10" /></map></template>',
'<template><area href="#section" shape="default" /></template>',
// Dynamic area href — skip.
'<template><area href={{this.url}} shape="rect" coords="0,0,1,1" /></template>',

// Non-scheme URLs that happen to contain `javascript:` are not javascript:
// URLs — they are relative paths or fragments. The URL parser resolves
// them against the base URL; no script runs.
'<template><a href="./javascript:foo">Relative path</a></template>',
'<template><a href="#javascript:foo">Fragment id</a></template>',
'<template><a href="/javascript:foo">Absolute path</a></template>',
'<template><a href="?q=javascript:foo">Query string</a></template>',
// `javascript` as a bare word (no colon) — treated as a relative path.
// Our regex only matches the `javascript:` scheme (with colon), so these pass.
'<template><a href="javascript">Relative</a></template>',
'<template><a href="javascriptFoo">Relative</a></template>',
],
invalid: [
// Plain "#" placeholder.
{
code: '<template><a href="#">Click</a></template>',
output: null,
errors: [{ messageId: 'invalidHref' }],
},
{
code: '<template><a href="#!">Click</a></template>',
output: null,
errors: [{ messageId: 'invalidHref' }],
},
// Empty / whitespace href.
{
code: '<template><a href="">Click</a></template>',
output: null,
errors: [{ messageId: 'invalidHref' }],
},
{
code: '<template><a href=" ">Click</a></template>',
output: null,
errors: [{ messageId: 'invalidHref' }],
},
{
code: '<template><a href>Click</a></template>',
output: null,
errors: [{ messageId: 'invalidHref' }],
},
// javascript: protocol.
{
code: '<template><a href="javascript:void(0)">Click</a></template>',
output: null,
errors: [{ messageId: 'invalidHref' }],
},
{
code: '<template><a href="JavaScript:alert(1)">Click</a></template>',
output: null,
errors: [{ messageId: 'invalidHref' }],
},
// Leading whitespace — catches obfuscations.
{
code: '<template><a href=" javascript:void(0)">Click</a></template>',
output: null,
errors: [{ messageId: 'invalidHref' }],
},
// Mustache-string-literal hrefs resolve to their static value via the
// shared `getStaticAttrValue` helper — the rule validates them the same
// as text-node values. Covers the common bypass hole where authors
// wrap a literal href in mustaches (`{{"#"}}`) to dodge a simple
// "is this a text node" check.
{
code: '<template><a href={{"#"}}>Click</a></template>',
output: null,
errors: [{ messageId: 'invalidHref' }],
},
{
code: '<template><a href={{"javascript:void(0)"}}>Click</a></template>',
output: null,
errors: [{ messageId: 'invalidHref' }],
},
// Single-part quoted-mustache (GlimmerConcatStatement wrapping a
// literal) resolves the same way.
{
code: '<template><a href="{{\'#\'}}">Click</a></template>',
output: null,
errors: [{ messageId: 'invalidHref' }],
},
// <area> shares <a>'s href semantics — same invalid values flag.
{
code: '<template><area href="#" shape="rect" coords="0,0,10,10" /></template>',
output: null,
errors: [{ messageId: 'invalidHref' }],
},
{
code: '<template><area href="" shape="rect" coords="0,0,10,10" /></template>',
output: null,
errors: [{ messageId: 'invalidHref' }],
},
{
code: '<template><area href="javascript:alert(1)" shape="rect" coords="0,0,10,10" /></template>',
output: null,
errors: [{ messageId: 'invalidHref' }],
},
],
});

const hbsRuleTester = new RuleTester({
parser: require.resolve('ember-eslint-parser/hbs'),
parserOptions: { ecmaVersion: 2022, sourceType: 'module' },
});

hbsRuleTester.run('template-no-invalid-link-href', rule, {
valid: ['<a href="/x">Link</a>', '<a href={{this.url}}>Link</a>', '<a>Not a link</a>'],
invalid: [
{
code: '<a href="#">Click</a>',
output: null,
errors: [{ messageId: 'invalidHref' }],
},
{
code: '<a href="javascript:void(0)">Click</a>',
output: null,
errors: [{ messageId: 'invalidHref' }],
},
],
});
Loading