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
6 changes: 4 additions & 2 deletions dist/core/rules/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

31 changes: 31 additions & 0 deletions src/core/rules/attr-no-protocol-relative-url.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Rule } from '../types'

export default {
id: 'attr-no-protocol-relative-url',
description:
'The src and href attributes must not use protocol-relative URLs.',
init(parser, reporter) {
parser.addListener('tagstart', (event) => {
const col = event.col + event.tagName.length + 1

for (const attr of event.attrs) {
const attrName = attr.name.toLowerCase()

if (
(attrName === 'src' || attrName === 'href') &&
// Match // after optional leading whitespace, e.g. "//cdn.example.com"
// or " //cdn.example.com", but not "https://cdn.example.com" or "/app.js".
/^\s*\/\//.test(attr.value)
) {
reporter.warn(
`The ${attr.name} attribute must use an explicit protocol instead of a protocol-relative URL.`,
event.line,
col + attr.index,
this,
attr.raw
)
}
}
})
},
} as Rule
1 change: 1 addition & 0 deletions src/core/rules/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export { default as altRequire } from './alt-require'
export { default as attrLowercase } from './attr-lowercase'
export { default as attrNoDuplication } from './attr-no-duplication'
export { default as attrNoProtocolRelativeUrl } from './attr-no-protocol-relative-url'
export { default as attrNoUnnecessaryWhitespace } from './attr-no-unnecessary-whitespace'
export { default as attrValueNoDuplication } from './attr-value-no-duplication'
export { default as attrSort } from './attr-sorted'
Expand Down
1 change: 1 addition & 0 deletions src/core/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export interface Ruleset {
'alt-require'?: boolean
'attr-lowercase'?: boolean | Array<string | RegExp>
'attr-no-duplication'?: boolean
'attr-no-protocol-relative-url'?: boolean
'attr-no-unnecessary-whitespace'?: boolean
'attr-sorted'?: boolean
'attr-unsafe-chars'?: boolean
Expand Down
126 changes: 126 additions & 0 deletions test/rules/attr-no-protocol-relative-url.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
const HTMLHint = require('../../dist/htmlhint.js').HTMLHint

const ruleId = 'attr-no-protocol-relative-url'
const ruleOptions = { [ruleId]: true }

describe(`Rules: ${ruleId}`, () => {
it('warns for the script and stylesheet examples from issue #348', () => {
const code =
'<script src="//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>\n' +
'<link rel="stylesheet" href="//use.fontawesome.com/releases/v5.8.2/css/all.css">'
const messages = HTMLHint.verify(code, ruleOptions)

expect(messages).toHaveLength(2)
expect(messages[0]).toMatchObject({
type: 'warning',
line: 1,
col: 8,
rule: { id: ruleId },
raw: ' src="//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"',
message:
'The src attribute must use an explicit protocol instead of a protocol-relative URL.',
})
expect(messages[1]).toMatchObject({
type: 'warning',
line: 2,
col: 23,
rule: { id: ruleId },
})
})

it.each(['src', 'SRC', 'sRc', 'href', 'HREF', 'hReF'])(
'checks the %s attribute regardless of case',
(name) => {
const messages = HTMLHint.verify(
`<a ${name}="//example.com"></a>`,
ruleOptions
)
expect(messages).toHaveLength(1)
expect(messages[0].rule.id).toBe(ruleId)
}
)

it.each([' ', '\t', '\n', '\r\n', '\f', ' \t\n '])(
'warns with leading whitespace %j',
(whitespace) => {
const code = `<img src="${whitespace}//example.com/photo.jpg">`
expect(HTMLHint.verify(code, ruleOptions)).toHaveLength(1)
}
)

it.each([
'<img src=//example.com/photo.jpg>',
"<a href='//example.com'>Link</a>",
])('checks single-quoted and unquoted values: %s', (code) => {
expect(HTMLHint.verify(code, ruleOptions)).toHaveLength(1)
})

describe.each(['src', 'href'])('allowed %s values', (name) => {
it.each([
'https://example.com/app.js',
'http://example.com/app.js',
'/assets/app.js',
'./app.js',
'../app.js',
'app.js',
'#content',
'?page=2',
'mailto:hello@example.com',
'tel:123456789',
'data:image/png;base64,AA',
'/redirect?url=//example.com',
' https://example.com/app.js',
'',
' ',
])('allows %j', (value) => {
const code = `<a ${name}="${value}"></a>`
expect(HTMLHint.verify(code, ruleOptions)).toHaveLength(0)
})
})

it('allows missing attributes and attributes without values', () => {
expect(HTMLHint.verify('<img><a src href></a>', ruleOptions)).toHaveLength(
0
)
})

it('ignores other attributes and CSS URLs', () => {
const code =
'<img srcset="//example.com/a.jpg 1x, //example.com/b.jpg 2x" data-src="//example.com/a.jpg">' +
'<form action="//example.com/submit"></form>' +
'<div style="background: url(//example.com/a.jpg)"></div>' +
'<style>body { background: url(//example.com/a.jpg); }</style>'
expect(HTMLHint.verify(code, ruleOptions)).toHaveLength(0)
})

it('reports every offending attribute', () => {
const code =
'<img src="//example.com/a.jpg"><a href="//example.com">Link</a>'
const messages = HTMLHint.verify(code, ruleOptions)
expect(messages).toHaveLength(2)
expect(messages[0].raw).toBe(' src="//example.com/a.jpg"')
expect(messages[1].raw).toBe(' href="//example.com"')
})

it('reports the location of an attribute on a multiline tag', () => {
const code = '<img\n alt="A mountain"\n src="//example.com/photo.jpg">'
const messages = HTMLHint.verify(code, ruleOptions)
expect(messages).toHaveLength(1)
expect(messages[0]).toMatchObject({
line: 3,
col: 1,
rule: { id: ruleId },
})
})

it('can be disabled explicitly', () => {
const code = '<script src="//example.com/app.js"></script>'
expect(HTMLHint.verify(code, { [ruleId]: false })).toHaveLength(0)
})

it('is disabled by default', () => {
const code = '<script src="//example.com/app.js"></script>'
const messages = HTMLHint.verify(code)
expect(messages.some((message) => message.rule.id === ruleId)).toBe(false)
})
})
1 change: 1 addition & 0 deletions website/src/content/docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ An example configuration file (with all rules disabled):
"alt-require": false,
"attr-lowercase": false,
"attr-no-duplication": false,
"attr-no-protocol-relative-url": false,
"attr-no-unnecessary-whitespace": false,
"attr-sorted": false,
"attr-unsafe-chars": false,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
---
id: attr-no-protocol-relative-url
title: attr-no-protocol-relative-url
description: Disallows protocol-relative URLs in src and href attributes.
pagefind: false
sidebar:
badge: New
Comment on lines +6 to +7
---

import { Badge } from '@astrojs/starlight/components';

The `src` and `href` attributes must not use URLs starting with `//`, including after leading whitespace.

Level: <Badge text="Warning" variant="caution" />

## Config value

- `true`: enable rule
- `false`: disable rule (default)

### The following patterns are **not** considered rule violations

```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="/assets/app.js"></script>
<a href="./about.html">About</a>
```

### The following patterns are considered rule violations

```html
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link
rel="stylesheet"
href="//use.fontawesome.com/releases/v5.8.2/css/all.css"
/>
```

## Why this rule is important

Protocol-relative URLs can load resources over HTTP. The [Google HTML/CSS Style Guide](https://google.github.io/styleguide/htmlcssguide.html#Protocol) recommends explicit HTTPS URLs when available.
1 change: 1 addition & 0 deletions website/src/content/docs/rules/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ description: A complete list of all the rules for HTMLHint
- [`alt-require`](alt-require/): The alt attribute of an img element must be present and alt attribute of area[href] and input[type=image] must have a value.
- [`attr-lowercase`](attr-lowercase/): All attribute names must be in lowercase.
- [`attr-no-duplication`](attr-no-duplication/): Elements cannot have duplicate attributes.
- [`attr-no-protocol-relative-url`](attr-no-protocol-relative-url/): The src and href attributes must not use protocol-relative URLs.
- [`attr-no-unnecessary-whitespace`](attr-no-unnecessary-whitespace/): No spaces between attribute names and values.
- [`attr-sorted`](attr-sorted/): Attributes should be sorted in order.
- [`attr-unsafe-chars`](attr-unsafe-chars/): Attribute values cannot contain unsafe chars.
Expand Down