diff --git a/WEB_TOPS.md b/WEB_TOPS.md index 7c117d4..bd0a7ec 100644 --- a/WEB_TOPS.md +++ b/WEB_TOPS.md @@ -295,7 +295,7 @@ A second adopter, an `astro-site` with tests or a `node-service` reopens the que and `laws`, and build output only where the class maps a build-output layer. It requires the judged laws it maps (§8.2, the tick column): the laws no class gates, plus its "Extra laws" row, with W-27 only when the project depends on Astro. `W-06 strict` for `node-service` is a reading of W-06, -which every class maps, as it does W-48 (unused exports, files and dependencies). A law a class maps but that has no reader yet (W-37, W-42 to W-48) is +which every class maps, as it does W-48 (unused exports, files and dependencies). A law a class maps but that has no reader yet (W-42 to W-48) is required when it is judged. Under `hard`, `check` refuses a coverage floor below, and a CRAP cap or `unexplained_survivors_max` above, the class's value in this table (§9, §12). @@ -788,7 +788,7 @@ These tables are generated from `laws/W-NN.yaml` (§8.3). Edit the file, not the | W-34 | No focused or skipped tests committed | R | tl: `@vitest/eslint-plugin` (1.6) `no-focused-tests`, `no-disabled-tests` | ✓ | | W-35 | Every suppression names its rule and says why: `eslint-disable` with a description, `@ts-expect-error` with a description, no `@ts-ignore` or `@ts-nocheck`; unused directives fail | R | tl: `eslint-comments/require-description`, `no-unlimited-disable`; `ban-ts-comment` (`allow-with-description`); `reportUnusedDisableDirectives: "error"`. The suppression census in §6.7 lists every kind that is counted and ratcheted | ✓ | | W-36 | No `set:html`, `dangerouslySetInnerHTML` or `innerHTML` with unsanitized input | R | an | | -| W-37 | Only public env reaches client code (`PUBLIC_` vars, `astro:env` client fields) | R | an | | +| W-37 | Only public env reaches client code (`PUBLIC_` vars, `astro:env` client fields) | R | an: custom ESLint rule, on `**/*.{jsx,tsx}` and `.astro` client script blocks (frontmatter is server code) | | | W-38 | No high or critical advisories in production dependencies | R | tl: dependency audit **[verify `bun audit` output]** | ✓ | | W-39 | No secrets in source or fixtures | R | tl: secrets scanner **[verify]** | | | W-40 | `bun.lock` is committed and installs with `--frozen-lockfile` | R | tl | ✓ | @@ -1131,6 +1131,7 @@ web-tops/ │ ├── report/ # report writing, text and JSON rendering │ └── survivors/ # the survivor key (section 6.4), and the ledger when it lands ├── profiles/ # one profile per launch class: the data init renders from +├── packages/ # eslint-plugin-webtops: the custom ESLint rules behind W-23, W-36 and W-37, built into the web-tops package ├── laws/ # one W-NN.yaml per law (§8.3): the source of the §8.2 tables ├── schema/ # web-tops, gate-report, baseline, core (verdicts, modes) and law schemas ├── config/ # drop-in templates, AGENTS.md.tmpl @@ -1146,7 +1147,7 @@ web-tops/ The law twins are in `fixtures/laws/W-NN/{bad,clean}/`: a bad and a clean twin per law, which the law probe (`src/laws/probe/`) proves. -Not yet in the tree: `src/budgets/` (the `dist/` byte reader, M4) and the M3 paths: `packages/eslint-plugin-webtops/`, `examples/node-service/`, `src/layers/laws/`, `src/acks/` and `src/lawdiff/`. The kit's tools already cover them: the M3 source paths and the plugin are linted, type-checked, formatted, cruised and tested like the rest of the source; the law fixtures are data, skipped like the probe fixtures; `examples/node-service` gates itself. +Not yet in the tree: `src/budgets/` (the `dist/` byte reader, M4) and the M3 paths: `examples/node-service/`, `src/layers/laws/`, `src/acks/` and `src/lawdiff/`. The kit's tools already cover them: the M3 source paths and the plugin are linted, type-checked, formatted, cruised and tested like the rest of the source; the law fixtures are data, skipped like the probe fixtures; `examples/node-service` gates itself. Self-hosting: the kit runs `hard` and passes its own tier-1 gate before any release. diff --git a/fixtures/init/astro-site/eslint.preset.json.golden b/fixtures/init/astro-site/eslint.preset.json.golden index 7cc32af..0314027 100644 --- a/fixtures/init/astro-site/eslint.preset.json.golden +++ b/fixtures/init/astro-site/eslint.preset.json.golden @@ -611,6 +611,14 @@ } } }, + { + "plugins": [ + "webtops" + ], + "rules": { + "webtops/no-unsanitized-html": "error" + } + }, { "files": [ "**/*.js", diff --git a/fixtures/init/node-service/eslint.preset.json.golden b/fixtures/init/node-service/eslint.preset.json.golden index e844a52..c4d320b 100644 --- a/fixtures/init/node-service/eslint.preset.json.golden +++ b/fixtures/init/node-service/eslint.preset.json.golden @@ -289,6 +289,14 @@ "vitest/no-disabled-tests": "error" } }, + { + "plugins": [ + "webtops" + ], + "rules": { + "webtops/no-unsanitized-html": "error" + } + }, { "files": [ "**/*.js", diff --git a/fixtures/init/ts-library/eslint.preset.json.golden b/fixtures/init/ts-library/eslint.preset.json.golden index e844a52..c4d320b 100644 --- a/fixtures/init/ts-library/eslint.preset.json.golden +++ b/fixtures/init/ts-library/eslint.preset.json.golden @@ -289,6 +289,14 @@ "vitest/no-disabled-tests": "error" } }, + { + "plugins": [ + "webtops" + ], + "rules": { + "webtops/no-unsanitized-html": "error" + } + }, { "files": [ "**/*.js", diff --git a/fixtures/init/ui-components/eslint.preset.json.golden b/fixtures/init/ui-components/eslint.preset.json.golden index 8afe878..4e431bb 100644 --- a/fixtures/init/ui-components/eslint.preset.json.golden +++ b/fixtures/init/ui-components/eslint.preset.json.golden @@ -411,6 +411,14 @@ "react-hooks/exhaustive-deps": "error" } }, + { + "plugins": [ + "webtops" + ], + "rules": { + "webtops/no-unsanitized-html": "error" + } + }, { "files": [ "**/*.js", diff --git a/fixtures/init/web-app/eslint.preset.json.golden b/fixtures/init/web-app/eslint.preset.json.golden index 8afe878..4e431bb 100644 --- a/fixtures/init/web-app/eslint.preset.json.golden +++ b/fixtures/init/web-app/eslint.preset.json.golden @@ -411,6 +411,14 @@ "react-hooks/exhaustive-deps": "error" } }, + { + "plugins": [ + "webtops" + ], + "rules": { + "webtops/no-unsanitized-html": "error" + } + }, { "files": [ "**/*.js", diff --git a/laws/W-37.yaml b/laws/W-37.yaml index ed25a44..373fc8e 100644 --- a/laws/W-37.yaml +++ b/laws/W-37.yaml @@ -6,7 +6,7 @@ severity: R classes: [ui-components, astro-site, web-app] reader: kinds: [an] - text: "an" + text: "an: custom ESLint rule, on `**/*.{jsx,tsx}` and `.astro` client script blocks (frontmatter is server code)" rules: - { tool: eslint, name: "webtops/public-env-only" } judged: m3 diff --git a/package.json b/package.json index 2f908a0..caa5353 100644 --- a/package.json +++ b/package.json @@ -43,6 +43,8 @@ "laws", "config", "profiles", + "packages/eslint-plugin-webtops/package.json", + "packages/eslint-plugin-webtops/dist", "fixtures/laws" ], "engines": { @@ -51,6 +53,7 @@ }, "packageManager": "bun@1.4.4", "scripts": { + "prepare": "tsc -p packages/eslint-plugin-webtops/tsconfig.build.json", "typecheck": "tsc -b --noEmit", "lint": "eslint .", "test": "vitest run --coverage --sequence.shuffle", diff --git a/packages/eslint-plugin-webtops/package.json b/packages/eslint-plugin-webtops/package.json new file mode 100644 index 0000000..7fa27d5 --- /dev/null +++ b/packages/eslint-plugin-webtops/package.json @@ -0,0 +1,26 @@ +{ + "name": "eslint-plugin-webtops", + "version": "0.3.0", + "private": true, + "description": "ESLint rules behind Web-TOPS laws W-23, W-36 and W-37 (complete Tailwind classes, no unsanitized HTML, public env only in client code)", + "license": "MIT OR Apache-2.0", + "type": "module", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "files": [ + "dist" + ], + "peerDependencies": { + "eslint": ">=10.15.0" + }, + "scripts": { + "build": "tsc -p tsconfig.build.json" + } +} diff --git a/packages/eslint-plugin-webtops/src/ast.test.ts b/packages/eslint-plugin-webtops/src/ast.test.ts new file mode 100644 index 0000000..cc97d09 --- /dev/null +++ b/packages/eslint-plugin-webtops/src/ast.test.ts @@ -0,0 +1,112 @@ +import { describe, expect, it } from "vitest"; +import { + attributeName, + attributeValue, + byKind, + child, + children, + dottedName, + kind, + lookup, + propertyName, + quasisOf, + staticText, + stringList, +} from "./ast.ts"; + +const id = (name: string) => ({ type: "Identifier", name }); +const member = (object: unknown, property: unknown, computed = false) => ({ + type: "MemberExpression", + object, + property, + computed, +}); +const literal = (value: unknown) => ({ type: "Literal", value }); + +describe("reading nodes by shape", () => { + it("takes a node's type and fields, and nothing from a value that is not a node", () => { + expect(kind(id("a"))).toBe("Identifier"); + expect(kind(null)).toBeUndefined(); + expect(kind("Identifier")).toBeUndefined(); + expect(kind({ type: 5 })).toBeUndefined(); + expect(child(null, "x")).toBeUndefined(); + expect(child({ x: 1 }, "x")).toBe(1); + }); + + it("reads a list field, and an empty list when it is absent or not a list", () => { + expect(children({ list: [1, 2] }, "list")).toEqual([1, 2]); + expect(children({}, "list")).toEqual([]); + expect(children({ list: "no" }, "list")).toEqual([]); + }); + + it("looks a node type or a name up in a table", () => { + const table = new Map([["Identifier", 1]]); + expect(byKind(table, id("a"))).toBe(1); + expect(byKind(table, literal("a"))).toBeUndefined(); + expect(byKind(table, null)).toBeUndefined(); + expect(lookup(table, "Identifier")).toBe(1); + expect(lookup(table, undefined)).toBeUndefined(); + }); + + it("gives the cooked text of each template part, and nothing for a part that cannot be cooked", () => { + const template = { + type: "TemplateLiteral", + quasis: [{ value: { cooked: "a" } }, { value: { cooked: null } }, { value: {} }], + expressions: [], + }; + expect(quasisOf(template)).toEqual(["a", "", ""]); + }); + + it("gives static text for a string literal and a template with no interpolation only", () => { + const plain = { + type: "TemplateLiteral", + quasis: [{ value: { cooked: "t" } }], + expressions: [], + }; + expect(staticText(literal("s"))).toBe("s"); + expect(staticText(literal(5))).toBeUndefined(); + expect(staticText(plain)).toBe("t"); + expect(staticText({ ...plain, expressions: [id("x")] })).toBeUndefined(); + expect(staticText(id("x"))).toBeUndefined(); + }); + + it("names an identifier, and a chain of plain member accesses", () => { + expect(dottedName(id("a"))).toBe("a"); + expect(dottedName(member(member(id("a"), id("b")), id("c")))).toBe("a.b.c"); + expect(dottedName(member(id("a"), literal("b"), true))).toBeUndefined(); + expect(dottedName(member(id("a"), id("b"), true))).toBeUndefined(); + expect(dottedName(member({ type: "ThisExpression" }, id("x")))).toBeUndefined(); + expect(dottedName(member(id("a"), { type: "PrivateIdentifier" }))).toBeUndefined(); + expect(dottedName(literal("a"))).toBeUndefined(); + }); + + it("names a property by identifier or by string key, and not by another computed key", () => { + expect(propertyName(member(id("a"), id("b")))).toBe("b"); + expect(propertyName(member(id("a"), literal("b"), true))).toBe("b"); + expect(propertyName(member(id("a"), id("b"), true))).toBeUndefined(); + }); + + it("names a JSX attribute, plain or namespaced, and reads its value", () => { + const plain = { type: "JSXAttribute", name: { type: "JSXIdentifier", name: "className" } }; + const spaced = { + type: "JSXAttribute", + name: { + type: "JSXNamespacedName", + namespace: { name: "set" }, + name: { name: "html" }, + }, + value: { type: "JSXExpressionContainer", expression: id("x") }, + }; + expect(attributeName(plain)).toBe("className"); + expect(attributeName(spaced)).toBe("set:html"); + expect(attributeName({ name: { type: "JSXNamespacedName" } })).toBe(":"); + expect(attributeValue(spaced)).toEqual(id("x")); + expect(attributeValue({ value: literal("a b") })).toEqual(literal("a b")); + }); + + it("takes only the strings of a list option, and the fallback when there is no list", () => { + expect(stringList({ names: ["a", 1, "b"] }, "names", ["z"])).toEqual(["a", "b"]); + expect(stringList({}, "names", ["z"])).toEqual(["z"]); + expect(stringList(undefined, "names", ["z"])).toEqual(["z"]); + }); +}); diff --git a/packages/eslint-plugin-webtops/src/ast.ts b/packages/eslint-plugin-webtops/src/ast.ts new file mode 100644 index 0000000..fe0fdf0 --- /dev/null +++ b/packages/eslint-plugin-webtops/src/ast.ts @@ -0,0 +1,111 @@ +/** + * A syntax node as the parser hands it over. ESLint's typings leave out JSX and Astro nodes, so the + * rules read every node by its shape: `type`, then the fields they care about. + */ +export type Loose = Readonly>; + +const isLoose = (value: unknown): value is Loose => typeof value === "object" && value !== null; + +/** The node's `type`, or undefined for anything that is not a node. */ +export function kind(node: unknown): string | undefined { + const type = isLoose(node) ? node["type"] : undefined; + return typeof type === "string" ? type : undefined; +} + +/** One field of a node, or undefined. */ +export const child = (node: unknown, key: string): unknown => + isLoose(node) ? node[key] : undefined; + +/** A list field of a node: empty when the field is absent or not a list. */ +export function children(node: unknown, key: string): readonly unknown[] { + const value = child(node, key); + return Array.isArray(value) ? value : []; +} + +/** The cooked text of a template element. */ +const cooked = (quasi: unknown): string | undefined => { + const text = child(child(quasi, "value"), "cooked"); + return typeof text === "string" ? text : undefined; +}; + +/** The static text of a template literal's parts: one string per quasi, `""` for a part the parser could not cook. */ +export const quasisOf = (template: unknown): readonly string[] => + children(template, "quasis").map((quasi) => cooked(quasi) ?? ""); + +const literalText = (node: unknown): string | undefined => { + const value = child(node, "value"); + return typeof value === "string" ? value : undefined; +}; + +const plainTemplateText = (node: unknown): string | undefined => + children(node, "expressions").length === 0 ? quasisOf(node)[0] : undefined; + +// Tables are built where they are used, not at module level: a mutant in module-level data runs +// the whole suite again (a static mutant), one in a function runs only the tests that reach it. +const textReaders = (): ReadonlyMap string | undefined> => + new Map([ + ["Literal", literalText], + ["TemplateLiteral", plainTemplateText], + ]); + +/** The entry of a table keyed by node type, for the node's own type. */ +export function byKind(table: ReadonlyMap, node: unknown): T | undefined { + const type = kind(node); + return type === undefined ? undefined : table.get(type); +} + +/** The entry of a table for a name that may be missing. */ +export const lookup = ( + table: ReadonlyMap, + name: string | undefined, +): T | undefined => (name === undefined ? undefined : table.get(name)); + +/** The text of a string literal or of a template literal with no interpolation; undefined for anything else. */ +export const staticText = (node: unknown): string | undefined => + byKind(textReaders(), node)?.(node); + +const joined = (object: string | undefined, property: string | undefined): string | undefined => + object !== undefined && property !== undefined ? `${object}.${property}` : undefined; + +const memberName = (node: unknown): string | undefined => + kind(node) === "MemberExpression" && child(node, "computed") !== true + ? joined(dottedName(child(node, "object")), nameOf(child(node, "property"))) + : undefined; + +/** `name` for an identifier, `a.b.c` for a chain of member accesses, else undefined. */ +export const dottedName = (node: unknown): string | undefined => + kind(node) === "Identifier" ? nameOf(node) : memberName(node); + +/** The `name` field of an identifier-like node. */ +export function nameOf(node: unknown): string | undefined { + const name = child(node, "name"); + return typeof name === "string" ? name : undefined; +} + +/** The name a property is read by: `a.b` and `a["b"]`; undefined for a computed key that is not a string literal. */ +export const propertyName = (member: unknown): string | undefined => + child(member, "computed") === true + ? staticText(child(member, "property")) + : nameOf(child(member, "property")); + +const namespaced = (name: unknown): string => + `${nameOf(child(name, "namespace")) ?? ""}:${nameOf(child(name, "name")) ?? ""}`; + +/** The attribute's name: `className`, or `set:html` for a namespaced one. */ +export function attributeName(attribute: unknown): string | undefined { + const name = child(attribute, "name"); + return kind(name) === "JSXNamespacedName" ? namespaced(name) : nameOf(name); +} + +/** The expression inside `attr={...}`, or the literal of `attr="..."`. */ +export function attributeValue(attribute: unknown): unknown { + const value = child(attribute, "value"); + return kind(value) === "JSXExpressionContainer" ? child(value, "expression") : value; +} + +/** Strings from a rule option that should be a list of them: anything else is dropped. */ +export function stringList(option: unknown, key: string, fallback: readonly string[]): string[] { + const value = child(option, key); + if (!Array.isArray(value)) return [...fallback]; + return value.filter((entry): entry is string => typeof entry === "string"); +} diff --git a/packages/eslint-plugin-webtops/src/index.test.ts b/packages/eslint-plugin-webtops/src/index.test.ts new file mode 100644 index 0000000..7fa69ca --- /dev/null +++ b/packages/eslint-plugin-webtops/src/index.test.ts @@ -0,0 +1,87 @@ +import { spawnSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { ESLint } from "eslint"; +import { afterAll, describe, expect, it } from "vitest"; +import plugin from "./index.ts"; + +const root = resolve(import.meta.dirname, ".."); +const made: string[] = []; +afterAll(() => { + for (const dir of made) rmSync(dir, { recursive: true, force: true }); +}); + +/** A value the test needs to be there. */ +function need(value: T | undefined): T { + if (value === undefined) throw new Error("expected a value"); + return value; +} + +const RULES = ["complete-tailwind-classes", "no-unsanitized-html", "public-env-only"]; + +describe("G6a: eslint-plugin-webtops", () => { + it("names itself and holds the three rules of W-23, W-36 and W-37", () => { + expect(plugin.meta).toEqual({ name: "eslint-plugin-webtops" }); + expect(Object.keys(plugin.rules ?? {}).sort()).toEqual(RULES); + }); + + it.each(RULES)("%s says which law it judges, and has a message and a schema", (name) => { + const meta = need(need(need(plugin.rules)[name]).meta); + expect(need(meta.docs).description).toMatch(/\(W-\d+\)$/u); + expect(Object.keys(need(meta.messages))).not.toHaveLength(0); + expect(need(meta.schema)).toBeDefined(); + }); + + it("has a manifest that exports the built entry and asks for ESLint 10", () => { + const manifest: unknown = JSON.parse(readFileSync(join(root, "package.json"), "utf8")); + expect(manifest).toMatchObject({ + name: "eslint-plugin-webtops", + type: "module", + exports: { ".": { default: "./dist/index.js" } }, + peerDependencies: { eslint: ">=10.15.0" }, + }); + }); + + it("is live in ESLint: a flat config that names the rules gets each of them reported", async () => { + const eslint = new ESLint({ + overrideConfigFile: true, + overrideConfig: { + files: ["**/*.jsx"], + plugins: { webtops: plugin }, + languageOptions: { parserOptions: { ecmaFeatures: { jsx: true } } }, + rules: { + "webtops/complete-tailwind-classes": "error", + "webtops/no-unsanitized-html": "error", + "webtops/public-env-only": "error", + }, + }, + }); + const code = [ + "export const A = ({ c, h }) =>
;", + "export const B = import.meta.env.SECRET;", + ].join("\n"); + const [result] = await eslint.lintText(code, { filePath: "a.jsx" }); + expect(result?.messages.map((message) => message.ruleId).sort()).toEqual( + RULES.map((name) => `webtops/${name}`), + ); + }); + + it("builds with tsc (types are checked by the gate's own tsc run), and the built package loads under Node", () => { + const out = mkdtempSync(join(tmpdir(), "wt-plugin-")); + made.push(out); + const tsc = resolve(root, "../../node_modules/.bin/tsc"); + const build = spawnSync(tsc, ["-p", "tsconfig.build.json", "--noCheck", "--outDir", out], { + cwd: root, + encoding: "utf8", + }); + expect(build.status, build.stdout + build.stderr).toBe(0); + const entry = JSON.stringify(join(out, "index.js")); + const script = `const p = (await import(${entry})).default; console.log(Object.keys(p.rules).sort().join());`; + const load = spawnSync("node", ["--input-type=module", "--eval", script], { + encoding: "utf8", + }); + expect(load.status, load.stderr).toBe(0); + expect(load.stdout.trim()).toBe(RULES.join()); + }, 60_000); +}); diff --git a/packages/eslint-plugin-webtops/src/index.ts b/packages/eslint-plugin-webtops/src/index.ts new file mode 100644 index 0000000..9205ea0 --- /dev/null +++ b/packages/eslint-plugin-webtops/src/index.ts @@ -0,0 +1,20 @@ +import type { ESLint } from "eslint"; +import completeTailwindClasses from "./rules/complete-tailwind-classes.ts"; +import noUnsanitizedHtml from "./rules/no-unsanitized-html.ts"; +import publicEnvOnly from "./rules/public-env-only.ts"; + +/** The rules behind Web-TOPS laws W-23, W-36 and W-37, under the `webtops` namespace. */ +const plugin: ESLint.Plugin = { + get meta() { + return { name: "eslint-plugin-webtops" }; + }, + get rules() { + return { + "complete-tailwind-classes": completeTailwindClasses, + "no-unsanitized-html": noUnsanitizedHtml, + "public-env-only": publicEnvOnly, + }; + }, +}; + +export default plugin; diff --git a/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.test.ts b/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.test.ts new file mode 100644 index 0000000..36e1498 --- /dev/null +++ b/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.test.ts @@ -0,0 +1,264 @@ +import { RuleTester } from "eslint"; +import { describe, expect, it } from "vitest"; +import rule from "./complete-tailwind-classes.ts"; + +RuleTester.describe = describe; +RuleTester.it = it; + +const tester = new RuleTester({ + languageOptions: { + ecmaVersion: "latest", + sourceType: "module", + parserOptions: { ecmaFeatures: { jsx: true } }, + }, +}); + +const incomplete = [{ messageId: "incomplete" as const }]; + +tester.run("complete-tailwind-classes", rule, { + valid: [ + { + name: "a non-plus operand inside a sum stays one operand", + code: '
', + }, + { name: "a subtraction is not a join", code: '
' }, + { + name: "an object with whole keys beside a plain one", + code: 'clsx({ "p-2": big, "m-2": small });', + }, + { name: "a template joined to a template", code: "
" }, + { name: "a whole class string", code: '
' }, + { name: "a lookup of complete strings", code: "
" }, + { + name: "whole tokens chosen by a condition", + code: '
', + }, + { name: "interpolated tokens are whole", code: "
" }, + { name: "an interpolation at the edges", code: "
" }, + { name: "a single interpolation", code: "
" }, + { + name: "a concatenation that keeps tokens whole", + code: '
', + }, + { name: "two static strings", code: '
' }, + { name: "the class attribute", code: '
' }, + { name: "an attribute that is not a class list", code: "
" }, + { name: "a name built outside a class list", code: "const id = `bg-${color}-500`;" }, + { name: "a call that is not a class helper", code: "other(`bg-${color}-500`);" }, + { + name: "a helper given whole strings", + code: 'clsx("flex", on && "bg-red-500", { "p-2": big });', + }, + { name: "a helper given a spread", code: "cn(...list);" }, + { name: "a member callee that is not a helper", code: "styles.pick(`bg-${c}`);" }, + { name: "a concat that keeps tokens whole", code: 'const a = "flex ".concat(extra);' }, + { + name: "an object key that is a plain string", + code: 'clsx({ "bg-red-500": on, [name]: off });', + }, + { + name: "a custom helper list leaves clsx alone", + code: "clsx(`bg-${c}`);", + options: [{ functions: ["tw"] }], + }, + { name: "a numeric addition", code: "
" }, + { name: "a template in a computed member", code: "
" }, + ], + invalid: [ + { + name: "a prefix joined with a non-plus operand", + code: '
', + errors: incomplete, + }, + { + name: "a glue after the last interpolation only", + code: "
", + errors: incomplete, + }, + { name: "classnames", code: "classnames(`bg-${c}`);", errors: incomplete }, + { name: "classNames", code: "classNames(`bg-${c}`);", errors: incomplete }, + { name: "twMerge", code: "twMerge(`bg-${c}`);", errors: incomplete }, + { name: "twJoin", code: "twJoin(`bg-${c}`);", errors: incomplete }, + { name: "tv", code: "tv(`bg-${c}`);", errors: incomplete }, + { + name: "one offending interpolation among whole ones", + code: "
", + errors: incomplete, + }, + { + name: "one offending part among whole ones in a sum", + code: '
', + errors: incomplete, + }, + { + name: "an offending key beside a plain one", + code: 'clsx({ [`bg-${c}`]: on, "p-2": off });', + errors: incomplete, + }, + { + name: "an offending key after a plain one", + code: 'clsx({ "p-2": off, [`bg-${c}`]: on });', + errors: incomplete, + }, + { + name: "a prefix joined with a sum", + code: '
', + errors: incomplete, + }, + { + name: "a glued suffix after an interpolation", + code: "
", + errors: incomplete, + }, + { + name: "an interpolation glued to a later one only", + code: "
", + errors: incomplete, + }, + { + name: "three interpolations, the last two glued", + code: "
", + errors: incomplete, + }, + { + name: "an interpolation glued to the one before it", + code: "
", + errors: incomplete, + }, + { + name: "interpolation inside a token", + code: "
", + errors: incomplete, + }, + { + name: "an interpolation that ends a token", + code: "
", + errors: incomplete, + }, + { + name: "an interpolation that starts a token", + code: "
", + errors: incomplete, + }, + { + name: "two interpolations glued", + code: "
", + errors: incomplete, + }, + { + name: "interpolation in the class attribute", + code: "
", + errors: incomplete, + }, + { + name: "concatenation of a prefix", + code: '
', + errors: incomplete, + }, + { + name: "concatenation of a suffix", + code: '
', + errors: incomplete, + }, + { + name: "concatenation in the middle of a chain", + code: '
', + errors: incomplete, + }, + { + name: "concatenation with a template prefix", + code: "
", + errors: incomplete, + }, + { + name: "interpolation in one branch", + code: '
', + errors: incomplete, + }, + { + name: "interpolation in the other branch", + code: '
', + errors: incomplete, + }, + { + name: "interpolation after &&", + code: "
", + errors: incomplete, + }, + { + name: "interpolation before ||", + code: '
', + errors: incomplete, + }, + { + name: "interpolation in an array", + code: '
', + errors: incomplete, + }, + { + name: "interpolation nested in an interpolation", + code: "
", + errors: incomplete, + }, + { + name: "concatenation inside an interpolation", + code: '
', + errors: incomplete, + }, + { name: "a concat call", code: '
', errors: incomplete }, + { + name: "a concat call with a suffix", + code: '
', + errors: incomplete, + }, + { + name: "clsx with an interpolated token", + code: "clsx(`bg-${color}-500`);", + errors: incomplete, + }, + { + name: "cn with a concatenated token", + code: 'cn("flex", "bg-" + color);', + errors: incomplete, + }, + { name: "an array argument", code: "cva([`bg-${c}`]);", errors: incomplete }, + { + name: "an object key built by interpolation", + code: "clsx({ [`bg-${c}`]: on });", + errors: incomplete, + }, + { name: "a nested helper call", code: "twMerge(clsx(`bg-${c}`));", errors: incomplete }, + { + name: "a member helper from the options", + code: "ui.tw(`bg-${c}`);", + options: [{ functions: ["ui.tw"] }], + errors: incomplete, + }, + { name: "a conditional argument", code: "cn(on ? `bg-${c}` : null);", errors: incomplete }, + ], +}); + +describe("the rule's own description", () => { + it("states what it judges, its option and its message", () => { + expect(rule.meta).toEqual({ + type: "problem", + docs: { + description: + "Tailwind class names are complete strings: no class token built by interpolation or concatenation (W-23)", + }, + schema: [ + { + type: "object", + properties: { + functions: { type: "array", items: { type: "string" }, uniqueItems: true }, + }, + additionalProperties: false, + }, + ], + messages: { + incomplete: + "Tailwind never sees a class name built at run time, so its style is missing in production. Write whole class names and choose between them with a lookup table.", + }, + }); + }); +}); diff --git a/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.ts b/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.ts new file mode 100644 index 0000000..c248f27 --- /dev/null +++ b/packages/eslint-plugin-webtops/src/rules/complete-tailwind-classes.ts @@ -0,0 +1,163 @@ +import type { Rule } from "eslint"; +import { + attributeName, + attributeValue, + byKind, + child, + children, + dottedName, + lookup, + propertyName, + quasisOf, + staticText, + stringList, +} from "../ast.ts"; + +/** W-23: a Tailwind class name is a complete string, never built by interpolation or concatenation. */ + +const isClassAttribute = (name: string | undefined): boolean => + name === "className" || name === "class"; + +const defaultHelpers = (): string[] => [ + "clsx", + "cn", + "classnames", + "classNames", + "twMerge", + "twJoin", + "cva", + "tv", +]; + +const endsInToken = (text: string | undefined): boolean => text !== undefined && /\S$/u.test(text); +const startsInToken = (text: string | undefined): boolean => + text !== undefined && /^\S/u.test(text); + +function templateBuildsToken(template: unknown): boolean { + const quasis = quasisOf(template); + const expressions = children(template, "expressions"); + const count = expressions.length; + // Static text ends in a token character before an interpolation, or starts with one after it, + // or two interpolations sit side by side (an empty text between them). + return ( + quasis.slice(0, count).some(endsInToken) || + quasis.slice(1, count + 1).some(startsInToken) || + quasis.slice(1, count).includes("") || + expressions.some(buildsToken) + ); +} + +/** Static text meets a computed part with no space between: `"bg-" + color`, `color + "-500"`. */ +function pairGlued(left: unknown, right: unknown): boolean { + const before = staticText(left); + const after = staticText(right); + return ( + (after === undefined && endsInToken(before)) || (before === undefined && startsInToken(after)) + ); +} + +const plusChain = (): ReadonlyMap readonly unknown[]> => + new Map([ + [ + "BinaryExpression", + (node) => + child(node, "operator") === "+" + ? [...operands(child(node, "left")), ...operands(child(node, "right"))] + : [node], + ], + ]); + +/** The operands of a chain of `+`, left to right; any other node is one operand. */ +function operands(node: unknown): readonly unknown[] { + return byKind(plusChain(), node)?.(node) ?? [node]; +} + +function partsBuildToken(parts: readonly unknown[]): boolean { + return ( + parts.slice(0, -1).some((part, index) => pairGlued(part, parts[index + 1])) || + parts.some(buildsToken) + ); +} + +/** Method calls that build a class string: `"bg-".concat(color)` joins like `+`, and `[...].join(" ")` builds from its items. */ +const methods = (): ReadonlyMap boolean> => + new Map([ + ["concat", (object, args) => partsBuildToken([object, ...args])], + ["join", (object) => buildsToken(object)], + ]); + +function methodBuildsToken(call: unknown): boolean { + const callee = child(call, "callee"); + const method = lookup(methods(), propertyName(callee)); + return method?.(child(callee, "object"), children(call, "arguments")) === true; +} + +/** A key that is not computed is an identifier or a literal, which cannot build a token. */ +const keyBuildsToken = (property: unknown): boolean => buildsToken(child(property, "key")); + +const checks = (): ReadonlyMap boolean> => + new Map([ + ["TemplateLiteral", templateBuildsToken], + [ + "BinaryExpression", + (node) => child(node, "operator") === "+" && partsBuildToken(operands(node)), + ], + ["CallExpression", methodBuildsToken], + [ + "ConditionalExpression", + (node) => buildsToken(child(node, "consequent")) || buildsToken(child(node, "alternate")), + ], + [ + "LogicalExpression", + (node) => buildsToken(child(node, "left")) || buildsToken(child(node, "right")), + ], + ["ArrayExpression", (node) => children(node, "elements").some(buildsToken)], + ["ObjectExpression", (node) => children(node, "properties").some(keyBuildsToken)], + ]); + +/** Whether an expression that ends up in a class list builds a class token at run time. */ +export const buildsToken = (node: unknown): boolean => byKind(checks(), node)?.(node) === true; + +const rule: Rule.RuleModule = { + get meta(): Rule.RuleMetaData { + return { + type: "problem", + docs: { + description: + "Tailwind class names are complete strings: no class token built by interpolation or concatenation (W-23)", + }, + schema: [ + { + type: "object", + properties: { + functions: { type: "array", items: { type: "string" }, uniqueItems: true }, + }, + additionalProperties: false, + }, + ], + messages: { + incomplete: + "Tailwind never sees a class name built at run time, so its style is missing in production. Write whole class names and choose between them with a lookup table.", + }, + }; + }, + create(context) { + const option: unknown = context.options[0]; + const helpers = new Set(stringList(option, "functions", defaultHelpers())); + return { + JSXAttribute(node: Rule.Node) { + if (isClassAttribute(attributeName(node)) && buildsToken(attributeValue(node))) { + context.report({ node, messageId: "incomplete" }); + } + }, + CallExpression(node) { + const callee = dottedName(node.callee); + if (callee !== undefined && helpers.has(callee) && node.arguments.some(buildsToken)) { + context.report({ node, messageId: "incomplete" }); + } + }, + }; + }, +}; + +export default rule; diff --git a/packages/eslint-plugin-webtops/src/rules/no-unsanitized-html.test.ts b/packages/eslint-plugin-webtops/src/rules/no-unsanitized-html.test.ts new file mode 100644 index 0000000..d266bb4 --- /dev/null +++ b/packages/eslint-plugin-webtops/src/rules/no-unsanitized-html.test.ts @@ -0,0 +1,192 @@ +import { RuleTester } from "eslint"; +import { describe, expect, it } from "vitest"; +import rule from "./no-unsanitized-html.ts"; + +RuleTester.describe = describe; +RuleTester.it = it; + +const tester = new RuleTester({ + languageOptions: { + ecmaVersion: "latest", + sourceType: "module", + parserOptions: { ecmaFeatures: { jsx: true } }, + }, +}); + +const DEFAULT = "sanitize, sanitizeHtml, DOMPurify.sanitize"; +const unsanitized = (sink: string, sanitizers = DEFAULT) => [ + { messageId: "unsanitized" as const, data: { sink, sanitizers } }, +]; + +tester.run("no-unsanitized-html", rule, { + valid: [ + { name: "a member that is not a sink, assigned a variable", code: "a.b = html;" }, + { name: "an identifier callee named like a sink", code: "insertAdjacentHTML(a, html);" }, + { + name: "a static HTML object", + code: '
x" }} />', + }, + { + name: "a template with no interpolation", + code: "
x` }} />", + }, + { + name: "a sanitized value", + code: "
", + }, + { + name: "DOMPurify", + code: "
", + }, + { + name: "sanitizeHtml", + code: "
", + }, + { name: "an empty object sets nothing", code: "
" }, + { + name: "an object with only another key", + code: "
", + }, + { name: "a static set:html", code: '
' }, + { name: "a sanitized set:html", code: "
" }, + { name: "both branches safe", code: '
"} />' }, + { name: "textContent is not a sink", code: "el.textContent = value;" }, + { name: "a static innerHTML", code: 'el.innerHTML = "x";' }, + { name: "a sanitized innerHTML", code: "el.innerHTML = sanitize(html);" }, + { name: "a sanitized outerHTML", code: "el.outerHTML = DOMPurify.sanitize(html);" }, + { + name: "a sanitized insertAdjacentHTML", + code: 'el.insertAdjacentHTML("beforeend", sanitize(html));', + }, + { name: "a static document.write", code: 'document.write("

");' }, + { name: "a call that is not a sink", code: "el.append(html);" }, + { name: "a plain call", code: "run(html);" }, + { name: "an attribute that is not a sink", code: "
" }, + { name: "a computed property that is not a sink", code: "el[name] = html;" }, + { + name: "a custom sanitizer", + code: "el.innerHTML = clean(html);", + options: [{ sanitizers: ["clean"] }], + }, + { name: "an assignment to a variable", code: "let x; x = html;" }, + { name: "a computed innerHTML with a literal", code: 'el["innerHTML"] = "";' }, + ], + invalid: [ + { + name: "a variable in dangerouslySetInnerHTML", + code: "
", + errors: unsanitized("dangerouslySetInnerHTML"), + }, + { + name: "a template with interpolation", + code: "
${x}` }} />", + errors: unsanitized("dangerouslySetInnerHTML"), + }, + { + name: "a props object that is not a literal", + code: "
", + errors: unsanitized("dangerouslySetInnerHTML"), + }, + { + name: "a call that is not a sanitizer", + code: "
", + errors: unsanitized("dangerouslySetInnerHTML"), + }, + { + name: "a member call that is not a sanitizer", + code: "
", + errors: unsanitized("dangerouslySetInnerHTML"), + }, + { + name: "one unsafe branch", + code: "
", + errors: unsanitized("dangerouslySetInnerHTML"), + }, + { + name: "a variable in set:html", + code: "
", + errors: unsanitized("set:html"), + }, + { + name: "set:html with an attribute string that is an expression", + code: "
${x}`} />", + errors: unsanitized("set:html"), + }, + { + name: "innerHTML with a variable", + code: "el.innerHTML = html;", + errors: unsanitized("innerHTML"), + }, + { + name: "innerHTML appended to", + code: "el.innerHTML += html;", + errors: unsanitized("innerHTML"), + }, + { + name: "outerHTML with a variable", + code: "el.outerHTML = html;", + errors: unsanitized("outerHTML"), + }, + { + name: "innerHTML set by a computed string key", + code: 'el["innerHTML"] = html;', + errors: unsanitized("innerHTML"), + }, + { + name: "innerHTML with a template", + code: "el.innerHTML = `${x}`;", + errors: unsanitized("innerHTML"), + }, + { + name: "insertAdjacentHTML with a variable", + code: 'el.insertAdjacentHTML("beforeend", html);', + errors: unsanitized("insertAdjacentHTML"), + }, + { + name: "insertAdjacentHTML with no markup argument", + code: 'el.insertAdjacentHTML("beforeend");', + errors: unsanitized("insertAdjacentHTML"), + }, + { + name: "document.write with a variable", + code: "document.write(html);", + errors: unsanitized("document.write"), + }, + { + name: "document.writeln with a variable", + code: "document.writeln(html);", + errors: unsanitized("document.writeln"), + }, + { + name: "a sanitizer the options replaced", + code: "el.innerHTML = sanitize(html);", + options: [{ sanitizers: ["clean"] }], + errors: unsanitized("innerHTML", "clean"), + }, + ], +}); + +describe("the rule's own description", () => { + it("states what it judges, its option and its message", () => { + expect(rule.meta).toEqual({ + type: "problem", + docs: { + description: + "No set:html, dangerouslySetInnerHTML or innerHTML with unsanitized input (W-36)", + }, + schema: [ + { + type: "object", + properties: { + sanitizers: { type: "array", items: { type: "string" }, uniqueItems: true }, + }, + additionalProperties: false, + }, + ], + messages: { + unsanitized: + "Unsanitized HTML reaches {{ sink }}. Pass a string literal, or the result of a sanitizer ({{ sanitizers }}).", + }, + }); + }); +}); diff --git a/packages/eslint-plugin-webtops/src/rules/no-unsanitized-html.ts b/packages/eslint-plugin-webtops/src/rules/no-unsanitized-html.ts new file mode 100644 index 0000000..482a983 --- /dev/null +++ b/packages/eslint-plugin-webtops/src/rules/no-unsanitized-html.ts @@ -0,0 +1,139 @@ +import type { Rule } from "eslint"; +import { + attributeName, + attributeValue, + byKind, + child, + children, + dottedName, + kind, + lookup, + nameOf, + propertyName, + staticText, + stringList, +} from "../ast.ts"; + +/** W-36: HTML reaches `set:html`, `dangerouslySetInnerHTML` or `innerHTML` only as a literal or through a sanitizer. */ + +const defaultSanitizers = (): string[] => ["sanitize", "sanitizeHtml", "DOMPurify.sanitize"]; + +/** Where markup goes in, and what is put there. */ +interface Sink { + readonly sink: string; + readonly html: unknown; +} + +type Safe = (node: unknown, sanitizers: ReadonlySet) => boolean; + +const safeChecks = (): ReadonlyMap => + new Map([ + [ + "CallExpression", + (node, sanitizers) => { + const callee = dottedName(child(node, "callee")); + return callee !== undefined && sanitizers.has(callee); + }, + ], + [ + "ConditionalExpression", + (node, sanitizers) => + isSafe(child(node, "consequent"), sanitizers) && + isSafe(child(node, "alternate"), sanitizers), + ], + ]); + +/** A literal, or the result of a sanitizer; a conditional is safe when both branches are. */ +export const isSafe = (node: unknown, sanitizers: ReadonlySet): boolean => + staticText(node) !== undefined || byKind(safeChecks(), node)?.(node, sanitizers) === true; + +/** What `dangerouslySetInnerHTML={{ __html: x }}` sets: `x`. A value that is not an object literal is its own payload, and an object with no `__html` sets nothing. */ +function htmlPayload(value: unknown): { html: unknown } | undefined { + if (kind(value) !== "ObjectExpression") return { html: value }; + const entry = children(value, "properties").find( + (property) => nameOf(child(property, "key")) === "__html", + ); + return entry === undefined ? undefined : { html: child(entry, "value") }; +} + +const attributeSinks = (): ReadonlyMap { html: unknown } | undefined> => + new Map([ + ["dangerouslySetInnerHTML", htmlPayload], + ["set:html", (value) => ({ html: value })], + ]); + +function attributeSink(attribute: unknown): Sink | undefined { + const name = attributeName(attribute); + const payload = lookup(attributeSinks(), name)?.(attributeValue(attribute)); + return name === undefined || payload === undefined ? undefined : { sink: name, ...payload }; +} + +function assignedSink(assignment: unknown): Sink | undefined { + const sink = propertyName(child(assignment, "left")); + return sink === "innerHTML" || sink === "outerHTML" + ? { sink, html: child(assignment, "right") } + : undefined; +} + +function insertedSink(call: unknown): Sink | undefined { + const callee = child(call, "callee"); + const inserts = propertyName(callee) === "insertAdjacentHTML"; + return inserts ? { sink: "insertAdjacentHTML", html: children(call, "arguments")[1] } : undefined; +} + +function writtenSink(call: unknown): Sink | undefined { + const name = dottedName(child(call, "callee")); + return name === "document.write" || name === "document.writeln" + ? { sink: name, html: children(call, "arguments")[0] } + : undefined; +} + +const callSink = (call: unknown): Sink | undefined => insertedSink(call) ?? writtenSink(call); + +const rule: Rule.RuleModule = { + get meta(): Rule.RuleMetaData { + return { + type: "problem", + docs: { + description: + "No set:html, dangerouslySetInnerHTML or innerHTML with unsanitized input (W-36)", + }, + schema: [ + { + type: "object", + properties: { + sanitizers: { type: "array", items: { type: "string" }, uniqueItems: true }, + }, + additionalProperties: false, + }, + ], + messages: { + unsanitized: + "Unsanitized HTML reaches {{ sink }}. Pass a string literal, or the result of a sanitizer ({{ sanitizers }}).", + }, + }; + }, + create(context) { + const option: unknown = context.options[0]; + const list = stringList(option, "sanitizers", defaultSanitizers()); + const sanitizers = new Set(list); + const inspect = (node: Rule.Node, found: Sink | undefined): void => { + if (found === undefined || isSafe(found.html, sanitizers)) return; + const data = { sink: found.sink, sanitizers: list.join(", ") }; + context.report({ node, messageId: "unsanitized", data }); + }; + return { + JSXAttribute: (node: Rule.Node) => { + inspect(node, attributeSink(node)); + }, + AssignmentExpression: (node) => { + inspect(node, assignedSink(node)); + }, + CallExpression: (node) => { + inspect(node, callSink(node)); + }, + }; + }, +}; + +export default rule; diff --git a/packages/eslint-plugin-webtops/src/rules/public-env-only.test.ts b/packages/eslint-plugin-webtops/src/rules/public-env-only.test.ts new file mode 100644 index 0000000..e586d64 --- /dev/null +++ b/packages/eslint-plugin-webtops/src/rules/public-env-only.test.ts @@ -0,0 +1,183 @@ +import { RuleTester } from "eslint"; +import { describe, expect, it } from "vitest"; +import rule from "./public-env-only.ts"; + +RuleTester.describe = describe; +RuleTester.it = it; + +const tester = new RuleTester({ + languageOptions: { ecmaVersion: "latest", sourceType: "module" }, +}); + +const privateName = (name: string) => [ + { messageId: "private" as const, data: { name, prefixes: "PUBLIC_" } }, +]; + +tester.run("public-env-only", rule, { + valid: [ + { name: "import.meta.url handed on", code: "send(import.meta.url);" }, + { name: "another member handed on", code: "send(other.value);" }, + { name: "a member of a call result", code: "send(a.env);" }, + { + name: "two prefixes, the second one matching", + code: "const a = process.env.B_KEY;", + options: [{ prefixes: ["A_", "B_"] }], + }, + { + name: "a public import.meta.env variable", + code: "const a = import.meta.env.PUBLIC_API_URL;", + }, + { name: "a public process.env variable", code: "const a = process.env.PUBLIC_API_URL;" }, + { name: "a built-in", code: "const a = import.meta.env.MODE + import.meta.env.BASE_URL;" }, + { + name: "every built-in", + code: "const a = [import.meta.env.DEV, import.meta.env.PROD, import.meta.env.SSR, import.meta.env.SITE];", + }, + { name: "a computed public name", code: 'const a = import.meta.env["PUBLIC_KEY"];' }, + { + name: "a destructured public variable", + code: "const { PUBLIC_KEY, MODE } = import.meta.env;", + }, + { + name: "a renamed destructured public variable", + code: "const { PUBLIC_KEY: key } = process.env;", + }, + { name: "the client module", code: 'import { PUBLIC_X } from "astro:env/client";' }, + { name: "another import", code: 'import { x } from "./x";' }, + { name: "another object named env", code: "const a = config.env.SECRET;" }, + { name: "another meta property", code: "const a = import.meta.url;" }, + { name: "another process property", code: "const a = process.argv;" }, + { + name: "a custom prefix", + code: "const a = process.env.NEXT_PUBLIC_KEY;", + options: [{ prefixes: ["NEXT_PUBLIC_"] }], + }, + { + name: "a custom allowed name", + code: "const a = process.env.NODE_ENV;", + options: [{ allowed: ["NODE_ENV"] }], + }, + { name: "a member of another object", code: "const a = other.SECRET;" }, + { + name: "a nested access on a public value", + code: "const a = process.env.PUBLIC_LIST.length;", + }, + ], + invalid: [ + { + name: "the env object as the init of a for loop", + code: "for (process.env; ; ) {}", + errors: [{ messageId: "whole" }], + }, + { + name: "the env object as a computed key", + code: "const a = x[process.env];", + errors: [{ messageId: "whole" }], + }, + { + name: "two prefixes are listed in the message", + code: "const a = process.env.KEY;", + options: [{ prefixes: ["A_", "B_"] }], + errors: [{ messageId: "private", data: { name: "KEY", prefixes: "A_, B_" } }], + }, + { + name: "a private import.meta.env variable", + code: "const a = import.meta.env.SECRET_KEY;", + errors: privateName("SECRET_KEY"), + }, + { + name: "a private process.env variable", + code: "const a = process.env.DATABASE_URL;", + errors: privateName("DATABASE_URL"), + }, + { + name: "a private variable by string key", + code: 'const a = process.env["DATABASE_URL"];', + errors: privateName("DATABASE_URL"), + }, + { + name: "a computed name", + code: "const a = import.meta.env[name];", + errors: [{ messageId: "dynamic" }], + }, + { + name: "a destructured private variable", + code: "const { SECRET } = import.meta.env;", + errors: privateName("SECRET"), + }, + { + name: "a renamed destructured private variable", + code: "const { SECRET: s } = process.env;", + errors: privateName("SECRET"), + }, + { + name: "a rest element", + code: "const { ...all } = process.env;", + errors: [{ messageId: "dynamic" }], + }, + { + name: "a computed pattern key", + code: "const { [name]: v } = process.env;", + errors: [{ messageId: "dynamic" }], + }, + { + name: "the whole object passed on", + code: "send(import.meta.env);", + errors: [{ messageId: "whole" }], + }, + { + name: "the whole process.env spread", + code: "const a = { ...process.env };", + errors: [{ messageId: "whole" }], + }, + { + name: "the server module", + code: 'import { SECRET } from "astro:env/server";', + errors: [{ messageId: "server", data: { name: "astro:env/server" } }], + }, + { + name: "a prefix the options replaced", + code: "const a = process.env.PUBLIC_KEY;", + options: [{ prefixes: ["NEXT_PUBLIC_"] }], + errors: [{ messageId: "private", data: { name: "PUBLIC_KEY", prefixes: "NEXT_PUBLIC_" } }], + }, + { + name: "a built-in the options removed", + code: "const a = import.meta.env.MODE;", + options: [{ allowed: [] }], + errors: privateName("MODE"), + }, + { + name: "two private variables", + code: "const a = [process.env.A, process.env.B];", + errors: [{ messageId: "private" }, { messageId: "private" }], + }, + ], +}); + +describe("the rule's own description", () => { + it("states what it judges, its options and its messages", () => { + const list = { type: "array", items: { type: "string" }, uniqueItems: true }; + expect(rule.meta).toEqual({ + type: "problem", + docs: { description: "Only public env reaches client code (W-37)" }, + schema: [ + { + type: "object", + properties: { prefixes: list, allowed: list }, + additionalProperties: false, + }, + ], + messages: { + private: + "{{ name }} is not a public variable (prefix {{ prefixes }}), so reading it in client code ships it to every visitor. Read it on the server.", + dynamic: + "An env variable read by a computed name cannot be checked, and may be private. Read a public variable by name.", + whole: + "The whole env object reaches client code. Read the public variables you need, by name.", + server: + "{{ name }} is a server-only module: its fields stay off the client. Use astro:env/client.", + }, + }); + }); +}); diff --git a/packages/eslint-plugin-webtops/src/rules/public-env-only.ts b/packages/eslint-plugin-webtops/src/rules/public-env-only.ts new file mode 100644 index 0000000..a7ae01d --- /dev/null +++ b/packages/eslint-plugin-webtops/src/rules/public-env-only.ts @@ -0,0 +1,90 @@ +import type { Rule } from "eslint"; +import { child, children, dottedName, kind, nameOf, propertyName, stringList } from "../ast.ts"; + +/** W-37: client code reads only public env: `PUBLIC_` variables, and `astro:env/client` fields. */ + +const defaultPrefixes = (): string[] => ["PUBLIC_"]; +/** What Vite and Astro define for every build, and none of it is a secret. */ +const builtIn = (): string[] => ["MODE", "DEV", "PROD", "SSR", "BASE_URL", "SITE"]; + +/** `process.env` or `import.meta.env`. */ +function isEnvObject(node: unknown): boolean { + const meta = kind(child(node, "object")) === "MetaProperty"; + return dottedName(node) === "process.env" || (meta && propertyName(node) === "env"); +} + +/** The key of a pattern property: `{ KEY }` and `{ KEY: alias }`; undefined for a computed or rest entry. */ +const patternKey = (property: unknown): string | undefined => + child(property, "computed") === true ? undefined : nameOf(child(property, "key")); + +const isChildOf = (parent: unknown, type: string, field: string, node: unknown): boolean => + kind(parent) === type && child(parent, field) === node; + +const rule: Rule.RuleModule = { + get meta(): Rule.RuleMetaData { + return { + type: "problem", + docs: { description: "Only public env reaches client code (W-37)" }, + schema: [ + { + type: "object", + properties: { + prefixes: { type: "array", items: { type: "string" }, uniqueItems: true }, + allowed: { type: "array", items: { type: "string" }, uniqueItems: true }, + }, + additionalProperties: false, + }, + ], + messages: { + private: + "{{ name }} is not a public variable (prefix {{ prefixes }}), so reading it in client code ships it to every visitor. Read it on the server.", + dynamic: + "An env variable read by a computed name cannot be checked, and may be private. Read a public variable by name.", + whole: + "The whole env object reaches client code. Read the public variables you need, by name.", + server: + "{{ name }} is a server-only module: its fields stay off the client. Use astro:env/client.", + }, + }; + }, + create(context) { + const option: unknown = context.options[0]; + const prefixes = stringList(option, "prefixes", defaultPrefixes()); + const allowed = new Set(stringList(option, "allowed", builtIn())); + const isPublic = (name: string): boolean => + allowed.has(name) || prefixes.some((prefix) => name.startsWith(prefix)); + const reportName = (node: Rule.Node, name: string | undefined): void => { + if (name === undefined) context.report({ node, messageId: "dynamic" }); + else if (!isPublic(name)) { + context.report({ + node, + messageId: "private", + data: { name, prefixes: prefixes.join(", ") }, + }); + } + }; + const inspectEnv = (node: Rule.Node): void => { + const parent: unknown = node.parent; + if (isChildOf(parent, "VariableDeclarator", "init", node)) { + children(child(parent, "id"), "properties").forEach((property) => { + reportName(node, patternKey(property)); + }); + } else if (!isChildOf(parent, "MemberExpression", "object", node)) { + context.report({ node, messageId: "whole" }); + } + }; + return { + ImportDeclaration(node) { + if (node.source.value === "astro:env/server") { + context.report({ node, messageId: "server", data: { name: "astro:env/server" } }); + } + }, + MemberExpression(node) { + if (isEnvObject(node.object)) reportName(node, propertyName(node)); + else if (isEnvObject(node)) inspectEnv(node); + }, + }; + }, +}; + +export default rule; diff --git a/packages/eslint-plugin-webtops/tsconfig.build.json b/packages/eslint-plugin-webtops/tsconfig.build.json new file mode 100644 index 0000000..317d713 --- /dev/null +++ b/packages/eslint-plugin-webtops/tsconfig.build.json @@ -0,0 +1,13 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "noEmit": false, + "outDir": "dist", + "rootDir": "src", + "declaration": true, + "rewriteRelativeImportExtensions": true, + "types": [] + }, + "include": ["src"], + "exclude": ["src/**/*.test.ts"] +} diff --git a/src/cli/layout.test.ts b/src/cli/layout.test.ts index 9c010ae..431c466 100644 --- a/src/cli/layout.test.ts +++ b/src/cli/layout.test.ts @@ -56,13 +56,7 @@ describe("G10a: section 17 matches the tree", () => { const paragraph = section.split("\n").find((line) => line.startsWith("Not yet in the tree")) ?? ""; const paths = [...paragraph.matchAll(/`([^`]+\/)`/g)].map((match) => match[1] ?? ""); - expect(paths).toEqual( - expect.arrayContaining([ - "src/budgets/", - "packages/eslint-plugin-webtops/", - "examples/node-service/", - ]), - ); + expect(paths).toEqual(expect.arrayContaining(["src/budgets/", "examples/node-service/"])); for (const path of paths) expect(existsSync(join(root, path)), path).toBe(false); }); }); diff --git a/src/presets/class-rules.test.ts b/src/presets/class-rules.test.ts new file mode 100644 index 0000000..21a3903 --- /dev/null +++ b/src/presets/class-rules.test.ts @@ -0,0 +1,83 @@ +import { readFileSync, readdirSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { describe, expect, it } from "vitest"; +import { parse } from "yaml"; +import plugin from "../../packages/eslint-plugin-webtops/src/index.ts"; +import { eslintPreset } from "./eslint.js"; +import type { EslintVariant } from "./eslint.js"; + +const ROOT = resolve(import.meta.dirname, "../.."); +const PREFIX = "webtops/"; +const CLASSES = ["ts-library", "ui-components", "astro-site", "web-app", "node-service"]; + +function yamlOf(path: string): unknown { + return parse(readFileSync(join(ROOT, path), "utf8")); +} + +function field(value: unknown, key: string): unknown { + return typeof value === "object" && value !== null ? Reflect.get(value, key) : undefined; +} + +function list(value: unknown, key: string): unknown[] { + const found = field(value, key); + return Array.isArray(found) ? found : []; +} + +/** The variant a class's drop-in profile names. */ +function variantOf(cls: string): EslintVariant { + const named = field(yamlOf(`profiles/${cls}.yaml`), "eslint"); + if (named === "base" || named === "react" || named === "astro") return named; + throw new Error(`profiles/${cls}.yaml names no variant`); +} + +/** The plugin's rules, named as a config names them. */ +const IMPLEMENTED = new Set(Object.keys(plugin.rules ?? {}).map((name) => `${PREFIX}${name}`)); + +/** + * The `webtops/*` rules the laws a class maps give the ESLint reader, read from the law files. A law + * can name a rule that a later step builds; the step that adds the rule to the plugin must also + * enable it, or this test fails. + */ +function mappedRules(cls: string): string[] { + const names = readdirSync(join(ROOT, "laws")) + .filter((file) => file.endsWith(".yaml")) + .map((file) => yamlOf(`laws/${file}`)) + .filter((law) => list(law, "classes").includes(cls)) + .flatMap((law) => list(law, "rules")) + .filter((rule) => field(rule, "tool") === "eslint") + .map((rule) => field(rule, "name")) + .filter((name): name is string => typeof name === "string" && IMPLEMENTED.has(name)); + return names.sort(); +} + +async function enabledRules(cls: string): Promise { + const config = await eslintPreset({ + variant: variantOf(cls), + tsconfigRootDir: "", + class: cls, + }); + const names = config.flatMap((entry) => + Object.entries(entry.rules ?? {}) + .filter(([name, setting]) => name.startsWith(PREFIX) && setting === "error") + .map(([name]) => name), + ); + return [...new Set(names)].sort(); +} + +describe("R98: a class's preset enables exactly the plugin rules its laws map", () => { + it.each(CLASSES)("%s: the enabled webtops/* rules are the mapped laws' rules", async (cls) => { + const mapped = mappedRules(cls); + expect(mapped.length).toBeGreaterThan(0); + expect(await enabledRules(cls)).toEqual(mapped); + }); + + it("holds the split the laws make: the Tailwind rule only for astro-site and web-app", async () => { + const withTailwind: string[] = []; + for (const cls of CLASSES) { + if ((await enabledRules(cls)).includes("webtops/complete-tailwind-classes")) { + withTailwind.push(cls); + } + } + expect(withTailwind).toEqual(["astro-site", "web-app"]); + }); +}); diff --git a/src/presets/eslint.d.ts b/src/presets/eslint.d.ts index 8c0f8ee..26f2de5 100644 --- a/src/presets/eslint.d.ts +++ b/src/presets/eslint.d.ts @@ -7,6 +7,8 @@ export interface EslintPresetOptions { readonly variant: EslintVariant; /** The project root, so the type-aware rules find its tsconfig. */ readonly tsconfigRootDir: string; + /** The project's class, which decides the rules of `eslint-plugin-webtops`; read from `web-tops.yaml` when left out. */ + readonly class?: string; } export const VARIANTS: readonly EslintVariant[]; diff --git a/src/presets/eslint.js b/src/presets/eslint.js index 69d494f..03fa48c 100644 --- a/src/presets/eslint.js +++ b/src/presets/eslint.js @@ -1,3 +1,6 @@ +import { existsSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; import eslintComments from "@eslint-community/eslint-plugin-eslint-comments"; import js from "@eslint/js"; import vitest from "@vitest/eslint-plugin"; @@ -54,6 +57,70 @@ const LAW_RULES = { const TSX = ["**/*.jsx", "**/*.tsx"]; +const PLUGIN_SOURCE = join( + import.meta.dirname, + "../../packages/eslint-plugin-webtops/src/index.ts", +); + +/** + * `eslint-plugin-webtops`, which ships inside this package: a published package has its build, and + * a checkout of the kit has the source, which Node reads as it is, so a test run needs no build. + */ +async function loadWebtops() { + const loaded = existsSync(PLUGIN_SOURCE) + ? await import(pathToFileURL(PLUGIN_SOURCE).href) + : await import("../../packages/eslint-plugin-webtops/dist/index.js"); + return loaded.default; +} + +const webtops = await loadWebtops(); + +/** eslint-plugin-astro lints each `