Skip to content

Commit 1ea94aa

Browse files
committed
fix(rules): count label elements in form-field-multiple-labels, skip readable alt in image-redundant-alt #1249 #1273
Signed-off-by: Nik Cubrilovic <[email protected]> (cherry picked from commit dee9d03)
1 parent 6c8eba6 commit 1ea94aa

7 files changed

Lines changed: 203 additions & 19 deletions

‎CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,11 @@ How it works:
2222
- Leaked-secret items now include the matched value's character length and zero-based source offset in `meta`; inline-script items also identify the script's position in the page. Values remain masked in reports. See [Leaked API key in client-side code](https://docs.squirrelscan.com/rules/security/leaked-secrets). (#1230)
2323
- **`squirrel audit` audits where a start URL redirects, not the redirector.** `squirrel audit bit.ly/abc` used to score bit.ly. The start URL's redirect chain is now resolved before anything is crawled, estimated or named, one request per hop through the same egress guard as the crawl, capped at 5 hops. A redirect within one site (`http` to `https`, apex to `www`, a path) is followed silently. A redirect to another registrable domain needs your consent: a terminal asks (`bit.ly/abc redirects to https://example.com/pricing. Audit example.com instead? [Y/n]`), and anything else needs `--follow-redirect` or `[crawler] follow_redirect = true`. Without it the run does not crawl or score the redirector: it exits `4` with a `redirected` report that names the destination, the chain and the command to run again, in every output format. `-y` does not imply the consent, because it approves credit spend and the redirect may land on a site that is not yours. A chain that detours through another domain and back counts as another site. Reports and prompts name each hop by scheme, host and path only, and the destination is audited at its origin and path: its query, fragment and userinfo are dropped, so a destination that needs them has to be audited by typing it directly. The hops are requested before the credit check and registration. A loop, a chain past 5 hops, or a hop into a private, link-local or metadata address also exits `4` and is never followed. A followed redirect is recorded in the report (`meta.originalUrl` and `meta.redirectChain` in JSON, a scan note in the text, markdown, LLM, XML and HTML reports), the project and the credit estimate are the destination's, and the MCP `audit_website` tool answers `confirmation_required` with the destination until called with `followRedirect: true`. See [Start URLs that redirect](https://docs.squirrelscan.com/cli/audit#start-urls-that-redirect). (#1281)
2424

25+
### Fixed
26+
27+
- **`a11y/form-field-multiple-labels` counts label elements, not references.** A `<label for="a">` that also wraps the control `id="a"` was counted twice and reported as "2 labels", which fires on every Shopify Dawn variant picker. Labels are now collected as a set the way a browser's `input.labels` does: one wrapping-and-`for` label is one label, a wrapping label whose `for` names another control does not label this one, and a wrapping label labels only its first labelable control. Two real labels on one control still warn with an accurate count. (#1249)
28+
- **`a11y/image-redundant-alt` no longer flags a readable alt that spells the filename.** `alt="Google Partner Logo"` on `google-partner-logo.svg` was reported only because both read the same once spaces and hyphens were removed. The filename test now needs the alt to look like a raw filename or slug (a single token, or the decoded filename spelled exactly), so `alt="arrow-downwards"` on `arrow-downwards.svg` still warns and the prefix, surrounding-text and figcaption checks are unchanged. (#1273)
29+
2530
## v0.0.141 (2026-10-29)
2631

2732
`squirrel audit --ephemeral` uses cloud features for one run and leaves nothing behind: the site is not added to the dashboard, scheduled or published unless you pass `--publish`. `--store-scripts` keeps the first-party scripts an audit fetched in the content store. Keyword-stuffing checks use the measured copy's own script, leaked-secret checks no longer flag credential key-name constants, and CI now rejects edits to tagged CHANGELOG sections.

‎docs/rules/a11y/form-field-multiple-labels.mdx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ Extra text about a field is a description, not a second name. That is what `aria
1313

1414
One check, `form-field-multiple-labels`, at severity warning. It covers every `<input>` except types `hidden`, `submit`, `button` and `reset`, plus every `<textarea>` and `<select>`.
1515

16-
For each control it counts every `<label for="...">` whose value matches the control's `id`, and adds one when the control has an ancestor `<label>`.
16+
For each control it counts the label elements that label it, the way a browser's `input.labels` does. That is every `<label for="...">` whose value matches the control's `id`, plus the ancestor `<label>` when that label has no `for` of its own and the control is its first labelable descendant. Each label element counts once: a `<label for="a">` that wraps the control with `id="a"` is one label, not two. A wrapping label whose `for` names another control does not label this one.
1717

1818
- Warn when the count is more than one. Report message: `N input(s) with multiple labels`. Items read `email (2 labels)`, naming the control by its `name`, falling back to its `id` and then its tag. Every offender is listed, and the finding carries the suggestion `Use aria-describedby for additional descriptions`.
1919
- Pass with `No inputs have multiple labels`.
@@ -29,7 +29,7 @@ For each control it counts every `<label for="...">` whose value matches the con
2929

3030
Keep one label and move the rest into `aria-describedby`. The description can point at several ids, so a hint and an error message can coexist.
3131

32-
A control wrapped in a `<label>` that also has a separate `<label for>` pointing at it is the usual shape, and it usually arrives when a wrapper is added for click-target reasons. Removing the wrapper `<label>` and keeping the explicit association fixes both.
32+
A control wrapped in a `<label>` that also has a separate, second `<label for>` pointing at it is the usual shape, and it usually arrives when a wrapper is added for click-target reasons. Removing the wrapper `<label>` and keeping the explicit association fixes both.
3333

3434
| | |
3535
|---|---|

‎docs/rules/a11y/image-redundant-alt.mdx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ The other kind of redundancy is duplication. Alt text that repeats the caption u
1414
One check, `image-redundant-alt`, at severity warning. It reads every `img[alt]` with a non-empty `alt` and runs four tests. An empty `alt`, which marks a decorative image, is skipped.
1515

1616
- The alt matches one of 42 patterns. Those cover the prefixes `image of`, `photo of`, `photograph of`, `picture of`, `graphic of`, `icon of`, `illustration of`, `diagram of`, `screenshot of`, `chart of`, `graph of`, `figure of` and `infographic of`, the bare nouns on their own, `logo`, `banner`, `img`, `thumbnail`, `hero image`, `cover image`, `featured image`, `placeholder`, `untitled`, `spacer`, `divider`, and bare file extensions such as `.jpg` and `.png`.
17-
- The alt matches the `src` filename. Both are lowercased and stripped of hyphens, underscores and spaces, and the filename must be longer than three characters. Item: `alt="hero-banner" matches filename`.
17+
- The alt is the `src` filename. Both are lowercased and stripped of hyphens, underscores and spaces, the filename (percent-escapes decoded, extension removed) must be longer than three characters, and the alt must look like a raw filename: a single token with no whitespace, or the decoded filename spelled exactly. A readable alt that merely spells the same words, such as `Google Partner Logo` for `google-partner-logo.svg`, is not flagged. Item: `alt="hero-banner" matches filename`.
1818
- The alt is repeated in the parent element's text. This needs the parent's text to be strictly longer than the alt and shorter than three times it, and the alt itself longer than ten characters, so a caption-sized repeat is caught while an exact-match parent and a long article are both left alone. Item: `"Annual revenue chart..." duplicates surrounding text`.
1919
- The alt is repeated in a `<figcaption>`. The image has to be inside a `<figure>`, the alt longer than five characters, and the caption has to equal or contain it. Item: `"Annual revenue chart..." duplicates figcaption`.
2020

@@ -34,7 +34,7 @@ Elements inside `<noscript>` are skipped: a browser with scripting enabled reads
3434

3535
Write what the image shows, not what kind of file it is. Where a caption already describes the image, the alt should add what the caption leaves out, or be empty if it adds nothing.
3636

37-
A logo whose correct alt is the company name, sitting in a file named after the company, trips the filename test. `<img src="northwind.svg" alt="Northwind">` is right, and reported.
37+
A logo whose correct alt is the company name as one word, sitting in a file named after the company, still trips the filename test. `<img src="northwind.svg" alt="Northwind">` is right, and reported. A multi-word alt such as `Northwind Traders logo` in `northwind-traders-logo.svg` is not.
3838

3939
| | |
4040
|---|---|

‎packages/rules/src/a11y/form-field-multiple-labels.ts‎

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22

33
import type { CheckResult, Rule, RuleContext, RuleResult } from "../types";
44

5+
/** Labelable elements, as HTML defines them (a label's first one is its control). */
6+
const LABELABLE =
7+
'input:not([type="hidden"]), button, meter, output, progress, select, textarea';
8+
59
export const formFieldMultipleLabelsRule: Rule = {
610
meta: {
711
id: "a11y/form-field-multiple-labels",
@@ -27,22 +31,34 @@ export const formFieldMultipleLabelsRule: Rule = {
2731

2832
const multipleLabels: string[] = [];
2933

34+
// `label[for]` elements by the id they point at, built once. Compared as
35+
// strings, never spliced into a selector: an id can hold any character.
36+
const labelsByFor = new Map<string, Element[]>();
37+
for (const label of doc.querySelectorAll("label[for]")) {
38+
const target = label.getAttribute("for");
39+
if (!target) continue;
40+
const list = labelsByFor.get(target);
41+
if (list) list.push(label);
42+
else labelsByFor.set(target, [label]);
43+
}
44+
3045
for (const input of inputs) {
3146
const id = input.getAttribute("id");
32-
let labelCount = 0;
3347

34-
// Check for label via for attribute
35-
if (id) {
36-
const labelsById = doc.querySelectorAll(`label[for="${id}"]`);
37-
labelCount += labelsById.length;
38-
}
48+
// The label ELEMENTS this control has, as `HTMLInputElement.labels` gives
49+
// them (#1249): a label that wraps the control and also points at it with
50+
// `for=` is one element, so it goes in a set once.
51+
const labels = new Set<Element>(id ? (labelsByFor.get(id) ?? []) : []);
3952

40-
// Check for wrapping label
41-
const parentLabel = input.closest("label");
42-
if (parentLabel) {
43-
labelCount++;
53+
// A wrapping label labels the control only when it has no `for` of its own
54+
// (a `for` naming another id sends the label there) and the control is its
55+
// first labelable descendant (HTML's labeled control rule).
56+
const wrapper = input.closest("label");
57+
if (wrapper && !wrapper.hasAttribute("for") && wrapper.querySelector(LABELABLE) === input) {
58+
labels.add(wrapper);
4459
}
4560

61+
const labelCount = labels.size;
4662
if (labelCount > 1) {
4763
const name =
4864
input.getAttribute("name") || id || input.tagName.toLowerCase();

‎packages/rules/src/a11y/image-redundant-alt.ts‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,15 @@ const redundantPatterns = [
5555
/^divider$/i,
5656
];
5757

58+
/** A filename stem with its percent-escapes decoded and lowercased; the raw stem when it will not decode. */
59+
function decodedStem(stem: string): string {
60+
try {
61+
return decodeURIComponent(stem).toLowerCase();
62+
} catch {
63+
return stem.toLowerCase();
64+
}
65+
}
66+
5867
export const imageRedundantAltRule: Rule = {
5968
meta: {
6069
id: "a11y/image-redundant-alt",
@@ -94,7 +103,11 @@ export const imageRedundantAltRule: Rule = {
94103
}
95104
}
96105

97-
// Check if alt duplicates filename
106+
// Check if alt is the filename itself (#1273). Equality after dropping
107+
// separators is not enough: "Google Partner Logo" for google-partner-logo.svg
108+
// is a readable description. It is redundant only when the alt is a raw
109+
// filename or slug: one token with no whitespace, or the decoded stem
110+
// spelled exactly.
98111
const src = img.getAttribute("src") || "";
99112
const filename =
100113
src
@@ -104,11 +117,13 @@ export const imageRedundantAltRule: Rule = {
104117
?.replace(/\.[^.]+$/, "") || "";
105118
if (filename && filename.length > 3) {
106119
const normalizedAlt = alt.toLowerCase().replace(/[-_\s]+/g, "");
107-
const normalizedFilename = filename
108-
.toLowerCase()
109-
.replace(/[-_\s]+/g, "");
120+
const stem = decodedStem(filename);
121+
const normalizedFilename = stem.replace(/[-_\s]+/g, "");
110122

111-
if (normalizedAlt === normalizedFilename) {
123+
if (
124+
normalizedAlt === normalizedFilename &&
125+
(!/\s/.test(alt) || alt.toLowerCase() === stem)
126+
) {
112127
redundantAlts.push(`alt="${alt}" matches filename`);
113128
}
114129
}
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
// a11y/form-field-multiple-labels counts label ELEMENTS (HTMLInputElement.labels), so a label that
2+
// wraps a control and also points at it with for= is one label (#1249).
3+
4+
import { describe, expect, test } from "bun:test";
5+
6+
import { parsePage } from "@squirrelscan/parser";
7+
8+
import { formFieldMultipleLabelsRule } from "../src/a11y/form-field-multiple-labels";
9+
import type { CheckResult, RuleContext } from "../src/types";
10+
11+
function run(body: string): CheckResult | undefined {
12+
const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Gift card amount selection form test page</title></head><body><main>${body}</main></body></html>`;
13+
const url = "https://example.com/";
14+
const ctx = {
15+
page: { url, html, statusCode: 200, loadTime: 0, headers: {} },
16+
parsed: parsePage(html, url),
17+
options: {},
18+
} as unknown as RuleContext;
19+
const result = formFieldMultipleLabelsRule.run(ctx);
20+
if (result instanceof Promise) throw new Error("form-field-multiple-labels is async");
21+
return result.checks.find((c) => c.name === "form-field-multiple-labels");
22+
}
23+
24+
describe("a11y/form-field-multiple-labels counts label elements (#1249)", () => {
25+
test("the reporter's gift card page passes", () => {
26+
const result = run(`<h1>Gift card</h1><form><fieldset><legend>Amount</legend>
27+
<label for="a"><input type="radio" name="amt" id="a" value="50"> 50</label>
28+
<label for="b"><input type="radio" name="amt" id="b" value="100"> 100</label>
29+
</fieldset></form>`);
30+
expect(result?.status).toBe("pass");
31+
expect(result?.items).toBeUndefined();
32+
});
33+
34+
test.each([
35+
["wrap only", `<label><input id="x" type="text"> X</label>`],
36+
["for only", `<label for="x">X</label><input id="x" type="text">`],
37+
["wrap plus for to itself", `<label for="x"><input id="x" type="text"> X</label>`],
38+
[
39+
"wrap plus for, no id to match twice",
40+
`<label for="x"><input id="x" name="n" type="text"></label>`,
41+
],
42+
])("%s passes", (_name, body) => {
43+
expect(run(body)?.status).toBe("pass");
44+
});
45+
46+
test("two label elements for one id still warn, with the real count", () => {
47+
const result = run(
48+
`<label for="y">One</label><label for="y">Two</label><input id="y" name="y" type="text">`,
49+
);
50+
expect(result?.status).toBe("warn");
51+
expect(result?.items?.[0]?.id).toBe("y (2 labels)");
52+
});
53+
54+
test("a wrapping label plus a separate label for= still warns", () => {
55+
const result = run(
56+
`<label>Wrap <input id="z" name="z" type="text"></label><label for="z">Other</label>`,
57+
);
58+
expect(result?.status).toBe("warn");
59+
expect(result?.items?.[0]?.id).toBe("z (2 labels)");
60+
});
61+
62+
test("a wrapping label whose for= points at another control does not label this one", () => {
63+
const result = run(
64+
`<label for="other">Other <input id="inner" name="inner" type="text"></label><input id="other" name="other" type="text"><label for="inner">Inner</label>`,
65+
);
66+
// `inner` is labelled by its for= label only; the wrapper belongs to `other`.
67+
expect(result?.status).toBe("pass");
68+
});
69+
70+
test("a wrapping label labels only its first labelable control", () => {
71+
const result = run(
72+
`<label>Both <input id="p" name="p" type="text"><input id="q" name="q" type="text"></label><label for="q">Q</label>`,
73+
);
74+
expect(result?.status).toBe("pass");
75+
});
76+
77+
test("an id with selector characters is matched literally", () => {
78+
const result = run(
79+
`<label for='a"]b'>A</label><label for='a"]b'>B</label><input id='a"]b' name="w" type="text">`,
80+
);
81+
expect(result?.status).toBe("warn");
82+
expect(result?.items?.[0]?.id).toBe("w (2 labels)");
83+
});
84+
});
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// a11y/image-redundant-alt: a readable alt that happens to spell the filename is not redundant;
2+
// a raw filename or slug used as the alt still is (#1273).
3+
4+
import { describe, expect, test } from "bun:test";
5+
6+
import { parsePage } from "@squirrelscan/parser";
7+
8+
import { imageRedundantAltRule } from "../src/a11y/image-redundant-alt";
9+
import type { CheckResult, RuleContext } from "../src/types";
10+
11+
function run(body: string): CheckResult | undefined {
12+
const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Descriptive partner logo alt fixture</title></head><body><main><h1>Certifications</h1>${body}</main></body></html>`;
13+
const url = "https://example.com/";
14+
const ctx = {
15+
page: { url, html, statusCode: 200, loadTime: 0, headers: {} },
16+
parsed: parsePage(html, url),
17+
options: {},
18+
} as unknown as RuleContext;
19+
const result = imageRedundantAltRule.run(ctx);
20+
if (result instanceof Promise) throw new Error("image-redundant-alt is async");
21+
return result.checks.find((c) => c.name === "image-redundant-alt");
22+
}
23+
24+
describe("a11y/image-redundant-alt readable alt vs filename (#1273)", () => {
25+
test("the reporter's Google Partner Logo fixture passes", () => {
26+
const result = run(`<img src="google-partner-logo.svg" alt="Google Partner Logo">`);
27+
expect(result?.status).toBe("pass");
28+
});
29+
30+
test("a distinct descriptive alt passes", () => {
31+
expect(run(`<img src="brand.svg" alt="Google Partner certification">`)?.status).toBe("pass");
32+
});
33+
34+
test.each([
35+
["slug equal to the filename", `<img src="arrow-downwards.svg" alt="arrow-downwards">`],
36+
["underscored stem", `<img src="hero_banner_v2.png" alt="hero_banner_v2">`],
37+
["camera name", `<img src="IMG_20240101.jpg" alt="IMG_20240101">`],
38+
["single token equal to the filename", `<img src="northwind.svg" alt="Northwind">`],
39+
[
40+
"a spaced filename spelled exactly",
41+
`<img src="my%20holiday%20photo.jpg" alt="my holiday photo">`,
42+
],
43+
])("still warns: %s", (_name, body) => {
44+
const result = run(body);
45+
expect(result?.status).toBe("warn");
46+
expect(result?.items?.some((i) => i.id.includes("matches filename"))).toBe(true);
47+
});
48+
49+
test("the figcaption control still warns", () => {
50+
const result = run(
51+
`<figure><img src="brand.svg" alt="Partner certification"><figcaption>Partner certification</figcaption></figure>`,
52+
);
53+
expect(result?.status).toBe("warn");
54+
expect(result?.items?.some((i) => i.id.includes("duplicates figcaption"))).toBe(true);
55+
});
56+
57+
test("the redundant-prefix and surrounding-text checks are unchanged", () => {
58+
expect(run(`<img src="a.jpg" alt="Photo of a squirrel">`)?.status).toBe("warn");
59+
expect(
60+
run(`<p>Annual revenue chart for 2024 <img src="b.jpg" alt="Annual revenue chart"></p>`)
61+
?.status,
62+
).toBe("warn");
63+
});
64+
});

0 commit comments

Comments
 (0)