From ac050b058f70729c1eb350c7817ad14f30c02766 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Sun, 15 Nov 2026 04:51:58 +0900 Subject: [PATCH 1/2] Add vocab-clone-verifier lint rule clone() on a vocabulary object does not inherit the source's default verifyPortableObject, so dereferencing through the copy with a get*() accessor may accept portable objects without verifying them. This is the mistake that PR #1396 made in the backfill package. The new @fedify/lint rule catches the common syntactic shape of it. The rule follows vocabulary objects within a file: parameters and variables annotated with @fedify/vocab types, objects constructed or parsed with a verifier, this/super in vocabulary subclasses, and the results of accessors and copies. It reports a clone() without a verifier whose copy is dereferenced by an accessor without one, once per clone() call, and offers an ESLint/Oxlint suggestion to use deepClone() instead, but no autofix, since deepClone() changes cost, caching, and signed representations and needs Fedify 2.5.0. The suggestion is withheld when a later clone() drops the verifier again and inside clone()/deepClone() overrides, where it would recurse. The rule is registered for ESLint (recommended: warn, strict: error) and Oxlint, but not for Deno Lint, which turns on every plugin rule and reports it as an error. The modules option adds other generated vocabulary modules, as for raw-property-iri-invalid. The stateless AST helpers shared with raw-property-iri-invalid are moved to lib/ast.ts without changing that rule's behavior. https://github.com/fedify-dev/fedify/issues/1401 Assisted-by: Claude Code:claude-opus-5-5 Assisted-by: Codex:gpt-6-astra Assisted-by: Antigravity:gemini-4-hydrogen Assisted-by: OpenCode:kimi-k3.1-pro Assisted-by: Claude Code:claude-fable-5-2 --- CHANGES.md | 13 + changes.d/lint/vocab-clone-verifier.md | 16 + claude-plugin/skills/fedify/SKILL.md | 4 + docs/manual/lint.md | 123 +++ packages/lint/README.md | 7 + packages/lint/src/index.ts | 2 + packages/lint/src/lib/ast.ts | 124 +++ packages/lint/src/lib/const.ts | 3 + packages/lint/src/lib/messages.ts | 13 + packages/lint/src/lib/raw-property-iri.ts | 108 +-- packages/lint/src/lib/vocab-clone.ts | 908 ++++++++++++++++++ packages/lint/src/mod.ts | 7 +- packages/lint/src/oxlint.ts | 2 + .../lint/src/rules/vocab-clone-verifier.ts | 75 ++ .../vocab-clone-verifier.registration.test.ts | 23 + .../src/tests/vocab-clone-verifier.test.ts | 680 +++++++++++++ 16 files changed, 2006 insertions(+), 102 deletions(-) create mode 100644 changes.d/lint/vocab-clone-verifier.md create mode 100644 packages/lint/src/lib/ast.ts create mode 100644 packages/lint/src/lib/vocab-clone.ts create mode 100644 packages/lint/src/rules/vocab-clone-verifier.ts create mode 100644 packages/lint/src/tests/vocab-clone-verifier.registration.test.ts create mode 100644 packages/lint/src/tests/vocab-clone-verifier.test.ts diff --git a/CHANGES.md b/CHANGES.md index 5f607a138..092ce1fa4 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -410,6 +410,17 @@ To be released. `as:content`, which are looked up literally. With ESLint and Oxlint, the `modules` option adds other vocabulary modules generated by `@fedify/vocab-tools` to the default `@fedify/vocab`. [[#1272], [#1356]] + - Added the `vocab-clone-verifier` rule, which warns when a `clone()` of + a vocabulary object is dereferenced through a `get*()` accessor without + a `verifyPortableObject` verifier. `clone()` does not inherit the default + verifier of the object it copies, so such a call may accept portable + objects without verifying them. Pass a verifier, such as a `Context`, to + `clone()`, or use `deepClone()` when the copy is used for dereferencing. + The rule is available in ESLint, where the recommended configuration + enables it as a warning, so projects that fail on warnings may see new + failures, and in Oxlint, where it has to be enabled by name. It is not + registered in Deno Lint, which reports every plugin rule as an error. + [[#1401], [#1443]] - Extended `raw-property-iri-invalid` to check `withRawProperty()` and static record and tuple keys passed to `withRawProperties()`. The rule reports invalid property IRIs and compact prefixes such as `as:content` @@ -418,7 +429,9 @@ To be released. [#1272]: https://github.com/fedify-dev/fedify/issues/1272 [#1355]: https://github.com/fedify-dev/fedify/issues/1355 [#1356]: https://github.com/fedify-dev/fedify/pull/1356 +[#1401]: https://github.com/fedify-dev/fedify/issues/1401 [#1420]: https://github.com/fedify-dev/fedify/pull/1420 +[#1443]: https://github.com/fedify-dev/fedify/pull/1443 ### @fedify/mysql diff --git a/changes.d/lint/vocab-clone-verifier.md b/changes.d/lint/vocab-clone-verifier.md new file mode 100644 index 000000000..4bbbe260a --- /dev/null +++ b/changes.d/lint/vocab-clone-verifier.md @@ -0,0 +1,16 @@ +--- +links: + '#1401': https://github.com/fedify-dev/fedify/issues/1401 + '#1443': https://github.com/fedify-dev/fedify/pull/1443 +--- + - Added the `vocab-clone-verifier` rule, which warns when a `clone()` of + a vocabulary object is dereferenced through a `get*()` accessor without + a `verifyPortableObject` verifier. `clone()` does not inherit the default + verifier of the object it copies, so such a call may accept portable + objects without verifying them. Pass a verifier, such as a `Context`, to + `clone()`, or use `deepClone()` when the copy is used for dereferencing. + The rule is available in ESLint, where the recommended configuration + enables it as a warning, so projects that fail on warnings may see new + failures, and in Oxlint, where it has to be enabled by name. It is not + registered in Deno Lint, which reports every plugin rule as an error. + [[#1401], [#1443]] diff --git a/claude-plugin/skills/fedify/SKILL.md b/claude-plugin/skills/fedify/SKILL.md index 0fcb53c6c..af93e6b8f 100644 --- a/claude-plugin/skills/fedify/SKILL.md +++ b/claude-plugin/skills/fedify/SKILL.md @@ -376,6 +376,10 @@ Keep property arrays stable during copying, including inside custom `clone()` overrides: `deepClone()` snapshots the existing indices of large sparse arrays. Entries added during copying are not visited, so their nested objects may remain shared. Copying preserves array length and holes. +Unlike `deepClone()`, `clone()` does not inherit the default +`verifyPortableObject`, so before dereferencing through a clone, pass +a verifier (a `Context` works) to `clone()` or use `deepClone()`. The +`@fedify/lint` rule `vocab-clone-verifier` warns about this pattern. To read a property that has no typed accessor, such as an application's extension, use `getRawPropertyValues(object, propertyIri)` or diff --git a/docs/manual/lint.md b/docs/manual/lint.md index ffb50c54a..3b4d688a4 100644 --- a/docs/manual/lint.md +++ b/docs/manual/lint.md @@ -27,6 +27,8 @@ The plugin includes rules that check for: - Public key and assertion method requirements - Collection filtering implementation - Deprecated Deno KV adapter usage + - Dereferencing through `clone()` copies that drop portable-object + verification [`@fedify/lint`]: https://jsr.io/@fedify/lint [ESLint]: https://eslint.org/ @@ -1893,6 +1895,127 @@ the default `@fedify/vocab` module specifiers there. Like other Deno Lint plugin rules, its reports are errors. ESLint's recommended configuration enables it as a warning; the strict configuration enables it as an error. +### `vocab-clone-verifier` + +*This rule is available since Fedify 2.5.0.* + +Warns when a `clone()` of a vocabulary object is dereferenced through +a `get*()` accessor, such as `getObject()` or `getContextHistory()`, without +a `verifyPortableObject` verifier. + +::: info +This rule is available in ESLint and Oxlint, but not in Deno Lint: Deno turns on +every rule of a plugin as soon as the plugin is listed and reports every plugin +rule as an error, so a heuristic warning could block CI. In ESLint, the +*recommended* configuration enables it as a warning and *strict* as an error. +In Oxlint, enable it by name. +::: + +**Why it matters:** +An object can remember a verifier that its accessors use by default when they +dereference portable objects (see +[*Default verifiers*](./vocab.md#default-verifiers)). Objects that Fedify +parses for you, such as activities that inboxes receive, have one. `clone()` +does not inherit it: the clone uses only the options passed to `clone()`, so an +accessor called on the clone may accept a portable object without verifying +it. `deepClone()` keeps each object's default (see +[*Deep copies*](./vocab.md#deep-copies)). + +~~~~ typescript +import type { Context } from "@fedify/fedify"; +import type { Note } from "@fedify/vocab"; + +async function history(ctx: Context, note: Note) { + // ❌ Reported: the clone does not inherit note's default verifier. + await note.clone().getContextHistory({ crossOrigin: "trust" }); + + // ✅ Pass a verifier, for example the context, to clone(): + await note.clone({}, ctx).getContextHistory({ crossOrigin: "trust" }); + + // ✅ Or keep the defaults with deepClone(): + await note.deepClone().getContextHistory({ crossOrigin: "trust" }); + + // ✅ Or pass a verifier to the accessor: + await note.clone().getContextHistory({ + crossOrigin: "trust", + verifyPortableObject: ctx.verifyPortableObject, + }); + + // ✅ Not reported: the clone is only serialized. + await note.clone({ content: "Edited" }).toJsonLd(); +} +~~~~ + +The rule only reads the code; it cannot see whether an object actually has +a default verifier at runtime, so its message says that the clone *may* skip +verification. It follows vocabulary objects that may have a default verifier: + + - Parameters and variables annotated with a type imported from + `@fedify/vocab` (also with `import type`, renamed imports such as + `import { Object as APObject }`, namespace imports such as `vocab.Note`, + and unions with `null` or `undefined`). + - Objects constructed with `new Note(values, options)`, + `Note.fromJsonLd(json, options)`, or `lookupObject(id, options)` whose + options are, or may be, a verifier, such as a `Context`. + - `this` and `super` in instance members of a class that extends + a vocabulary class. + - Results of `get*()` accessors, `deepClone()`, and `clone()` with + a verifier, on such objects, including through `const` aliases and + `for await` loops. + +It reports a `clone()` whose options pass no verifier when the copy is then +used to call a `get*()` accessor whose options pass no verifier either. +Options that are not an object literal, such as a `Context` or a variable, are +assumed to pass a verifier. An explicit `verifyPortableObject: undefined` or +`null` is taken as a deliberate choice and not reported, and neither is an +accessor called with `dereference: false`. Each `clone()` is reported once, +even if its copy is dereferenced several times. If the copy is cloned again +without a verifier before it is dereferenced, the rule reports the first +`clone()` and says that every copy has to keep the verifier. + +ESLint and Oxlint offer an editor suggestion that replaces `clone()` with +`deepClone()`, but never an automatic fix: `deepClone()` copies the whole +object graph, which can be much more expensive, drops cached JSON-LD and signed +representations, which can change serialization and signature validity, and is +only available since Fedify 2.5.0. Passing a verifier to `clone()` is often the +cheaper fix. + +The analysis is limited to what it can follow syntactically within a file: + + - It does not follow values through function calls, return values, object + properties such as `this.note`, or other modules, and does not use type + information. Variables that are reassigned are not followed. + - Activities that inbox listeners receive and results of + `~Context.lookupObject()` are not followed unless they are annotated with + a vocabulary type. + - Calling a plural accessor, such as `getAttachments()`, counts as + dereferencing even if the returned iterable is never consumed. + - Custom `clone()` overrides and custom `get*()` methods of subclasses are + treated like the generated ones. + - An accessor called on a copy is reported even if the property is already + embedded or cached, so that nothing would be fetched. + - Conditional and logical expressions, such as `a ?? b`, are not followed. + - Type parameters and local types are not told apart from imported + vocabulary types of the same name. + +By default, only imports from `@fedify/vocab` are followed, including +`jsr:`/`npm:` and versioned specifiers, and the deprecated +`@fedify/fedify/vocab` re-export. For other vocabulary modules generated with +`@fedify/vocab-tools`, add their exact import specifiers to `modules`, in the +same way as for [`raw-property-iri-invalid`](#raw-property-iri-invalid): + +~~~~ jsonc +// .oxlintrc.json +{ + "jsPlugins": ["@fedify/lint/oxlint"], + "rules": { + "@fedify/lint/vocab-clone-verifier": ["warn", { + "modules": ["@example/vocab"] + }] + } +} +~~~~ + ### `deno-kv-store-deprecated` Warns when `DenoKvStore` from the deprecated *@fedify/denokv* package is diff --git a/packages/lint/README.md b/packages/lint/README.md index 2ac96226d..f0ec394f6 100644 --- a/packages/lint/README.md +++ b/packages/lint/README.md @@ -20,6 +20,8 @@ The plugin includes rules that check for: - Public key and assertion method requirements - Collection filtering implementation - Full property IRIs for raw-property helpers (`raw-property-iri-invalid`) + - Dereferencing through `clone()` copies that drop portable-object + verification (`vocab-clone-verifier`) [npm badge]: https://img.shields.io/npm/v/@fedify/lint?logo=npm [npm]: https://www.npmjs.com/package/@fedify/lint @@ -150,6 +152,11 @@ gateway-compatible IDs. full `http:` or `https:` IRI, e.g., a term or a compact IRI like `as:content`; the `modules` option, available in ESLint and Oxlint only, adds other generated vocabulary modules to `@fedify/vocab` + - **`vocab-clone-verifier`**: Warns when a `clone()` of a vocabulary object, + which does not inherit the object's default `verifyPortableObject`, is + dereferenced through a `get*()` accessor without a verifier; pass + a verifier, such as a `Context`, to `clone()`, or use `deepClone()` + (ESLint and Oxlint only) ### Deprecation rules diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index eb994c35b..baf602c36 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -40,6 +40,7 @@ import { eslint as outboxListenerDeliveryNotAwaited } from "./rules/outbox-liste import { eslint as outboxListenerDeliveryRequired } from "./rules/outbox-listener-delivery-required.ts"; import { eslint as rawPropertyIriInvalid } from "./rules/raw-property-iri-invalid.ts"; +import { eslint as vocabCloneVerifier } from "./rules/vocab-clone-verifier.ts"; const rules: Record<(typeof RULE_IDS)[keyof typeof RULE_IDS], Rule.RuleModule> = { @@ -83,6 +84,7 @@ const rules: Record<(typeof RULE_IDS)[keyof typeof RULE_IDS], Rule.RuleModule> = mediaUploaderAuthorizationRequired, [RULE_IDS.denoKvStoreDeprecated]: denoKvStoreDeprecated, [RULE_IDS.denoKvMessageQueueDeprecated]: denoKvMessageQueueDeprecated, + [RULE_IDS.vocabCloneVerifier]: vocabCloneVerifier, }; const recommendedRuleIds: (keyof typeof rules)[] = [ diff --git a/packages/lint/src/lib/ast.ts b/packages/lint/src/lib/ast.ts new file mode 100644 index 000000000..bc355e20c --- /dev/null +++ b/packages/lint/src/lib/ast.ts @@ -0,0 +1,124 @@ +/** + * Structural AST helpers shared by rules that analyze a whole program. A + * structural view keeps the analysis independent of the three AST providers: + * typescript-eslint (ESLint), Oxlint, and Deno Lint. + * @module + */ + +/** A structural view of an AST node from any of the supported providers. */ +export type Ast = { type: string; [key: string]: unknown }; +/** TypeScript and parenthesis wrappers that pass a value through unchanged. */ +export const expressionWrappers: ReadonlySet = new Set([ + "TSAsExpression", + "TSSatisfiesExpression", + "TSNonNullExpression", + "TSTypeAssertion", + "ParenthesizedExpression", +]); +/** Returns `value` as a node if it looks like one. */ +export function ast(value: unknown): Ast | undefined { + return value != null && + typeof value === "object" && + typeof (value as Ast).type === "string" + ? (value as Ast) + : undefined; +} +/** Strips {@link expressionWrappers} around an expression. */ +export function unwrap(node: Ast | undefined): Ast | undefined { + while (node && expressionWrappers.has(node.type)) node = ast(node.expression); + return node; +} +/** The name of an identifier, or the value of a string literal. */ +export function name(value: unknown): string | undefined { + const node = ast(value); + return node?.type === "Identifier" + ? (node.name as string) + : typeof node?.value === "string" + ? node.value + : undefined; +} +/** + * The child nodes of `node`, never following parent pointers. Deno exposes + * AST fields through non-enumerable getters, so the standard child fields are + * listed explicitly; type annotations are not traversed. + */ +export function children(node: Ast): Ast[] { + const result: Ast[] = []; + // Deno exposes AST fields through non-enumerable getters. Include its + // standard child fields explicitly, while retaining parser-specific fields + // from ESTree providers. Never follow parent pointers. + const keys = new Set([ + ...Object.keys(node), + "declaration", + "openingElement", + "closingElement", + "attributes", + "decorators", + "parameter", + "body", + "expression", + "expressions", + "declarations", + "id", + "init", + "params", + "param", + "callee", + "arguments", + "object", + "property", + "key", + "value", + "properties", + "elements", + "left", + "right", + "argument", + "test", + "consequent", + "alternate", + "block", + "handler", + "finalizer", + "cases", + "discriminant", + "update", + "specifiers", + "local", + "imported", + "source", + "superClass", + "tag", + "quasi", + "quasis", + "children", + "members", + "initializer", + ]); + for (const key of keys) { + // ESTree providers attach the token and comment arrays to Program: + if (key === "parent" || key === "tokens" || key === "comments") continue; + const value = node[key]; + if (Array.isArray(value)) { + for (const item of value) { + const child = ast(item); + if (child) result.push(child); + } + } else { + const child = ast(value); + if (child) result.push(child); + } + } + return result; +} +/** + * Whether `source` is an import specifier of Fedify's built-in vocabulary + * module: `@fedify/vocab`, or the deprecated `@fedify/fedify/vocab` + * re-export, including `jsr:`/`npm:` prefixed and versioned forms. + */ +export function isVocabularySource(source: string): boolean { + return ( + /^(?:jsr:|npm:)?@fedify\/vocab(?:@[^/]+)?$/.test(source) || + /^(?:jsr:|npm:)?@fedify\/fedify(?:@[^/]+)?\/vocab$/.test(source) + ); +} diff --git a/packages/lint/src/lib/const.ts b/packages/lint/src/lib/const.ts index 2fc3d0c27..23d0b8027 100644 --- a/packages/lint/src/lib/const.ts +++ b/packages/lint/src/lib/const.ts @@ -187,6 +187,9 @@ export const RULE_IDS = { rawPropertyIriInvalid: "raw-property-iri-invalid", + // Vocabulary rules + vocabCloneVerifier: "vocab-clone-verifier", + // Deprecation rules denoKvStoreDeprecated: "deno-kv-store-deprecated", denoKvMessageQueueDeprecated: "deno-kv-message-queue-deprecated", diff --git a/packages/lint/src/lib/messages.ts b/packages/lint/src/lib/messages.ts index 5533addce..a7ef76f45 100644 --- a/packages/lint/src/lib/messages.ts +++ b/packages/lint/src/lib/messages.ts @@ -100,3 +100,16 @@ export const RAW_PROPERTY_IRI_MESSAGES = { 'Raw property IRI "{{value}}" uses a non-HTTP scheme. Prefixes are not expanded.{{hint}}', expandPrefix: 'Use the full IRI "{{replacement}}".', }; + +/** + * Messages for the `vocab-clone-verifier` rule. They say that `clone()` does + * not inherit the verifier, never that an object is unverified: whether the + * source has a default verifier is runtime state that the rule cannot see. + */ +export const VOCAB_CLONE_VERIFIER_MESSAGES = { + dropsVerifier: + "`clone()` does not inherit this object's default `verifyPortableObject`, so a `get*()` call through the copy may skip portable-object verification. Pass `verifyPortableObject` (for example, a `Context`) to `clone()`, or use `deepClone()` when the copy is used for dereferencing.", + dropsVerifierRechained: + "`clone()` does not inherit this object's default `verifyPortableObject`, and a later `clone()` in the chain drops it again, so a `get*()` call through the copy may skip portable-object verification. Pass `verifyPortableObject` (for example, a `Context`) to the last `clone()`, or use `deepClone()` for every copy used for dereferencing.", + useDeepClone: "Use `deepClone()` when dereferencing through the copy.", +}; diff --git a/packages/lint/src/lib/raw-property-iri.ts b/packages/lint/src/lib/raw-property-iri.ts index c61fb85bf..7c455e239 100644 --- a/packages/lint/src/lib/raw-property-iri.ts +++ b/packages/lint/src/lib/raw-property-iri.ts @@ -1,3 +1,11 @@ +import { + ast, + type Ast, + children, + isVocabularySource as isBuiltinVocabularySource, + name, + unwrap, +} from "./ast.ts"; import type { Node } from "./types.ts"; /** Options for checking additional generated vocabulary modules. */ @@ -14,8 +22,6 @@ export interface RawPropertyIriDiagnostic { suggestionNode?: Node; } -// A structural view keeps the analysis independent of the three AST providers. -type Ast = { type: string; [key: string]: unknown }; interface Binding { imported?: string; namespace?: boolean; @@ -35,13 +41,6 @@ const functions = new Set([ "withRawProperty", "withRawProperties", ]); -const expressionWrappers = new Set([ - "TSAsExpression", - "TSSatisfiesExpression", - "TSNonNullExpression", - "TSTypeAssertion", - "ParenthesizedExpression", -]); const prefixes: Readonly> = { as: "https://www.w3.org/ns/activitystreams#", dcterms: "http://purl.org/dc/terms/", @@ -55,17 +54,6 @@ const prefixes: Readonly> = { vcard: "http://www.w3.org/2006/vcard/ns#", }; -function ast(value: unknown): Ast | undefined { - return value != null && - typeof value === "object" && - typeof (value as Ast).type === "string" - ? (value as Ast) - : undefined; -} -function unwrap(node: Ast | undefined): Ast | undefined { - while (node && expressionWrappers.has(node.type)) node = ast(node.expression); - return node; -} function primitivePropertyKey(node: Ast): string | undefined { if (node.type !== "Literal" || node.regex != null) return; if (typeof node.value === "bigint") return String(node.value); @@ -90,83 +78,6 @@ function primitivePropertyKey(node: Ast): string | undefined { if (node.value === null || typeof node.value === "boolean") return String(node.value); } -function name(value: unknown): string | undefined { - const node = ast(value); - return node?.type === "Identifier" - ? (node.name as string) - : typeof node?.value === "string" - ? node.value - : undefined; -} -function children(node: Ast): Ast[] { - const result: Ast[] = []; - // Deno exposes AST fields through non-enumerable getters. Include its - // standard child fields explicitly, while retaining parser-specific fields - // from ESTree providers. Never follow parent pointers. - const keys = new Set([ - ...Object.keys(node), - "declaration", - "openingElement", - "closingElement", - "attributes", - "decorators", - "parameter", - "body", - "expression", - "expressions", - "declarations", - "id", - "init", - "params", - "param", - "callee", - "arguments", - "object", - "property", - "key", - "value", - "properties", - "elements", - "left", - "right", - "argument", - "test", - "consequent", - "alternate", - "block", - "handler", - "finalizer", - "cases", - "discriminant", - "update", - "specifiers", - "local", - "imported", - "source", - "superClass", - "tag", - "quasi", - "quasis", - "children", - "members", - "initializer", - ]); - for (const key of keys) { - // ESTree providers attach the token and comment arrays to Program: - if (key === "parent" || key === "tokens" || key === "comments") continue; - const value = node[key]; - if (Array.isArray(value)) { - for (const item of value) { - const child = ast(item); - if (child) result.push(child); - } - } else { - const child = ast(value); - if (child) result.push(child); - } - } - return result; -} function bind(pattern: unknown, scope: Scope, binding: Binding = {}): void { const node = ast(pattern); if (!node) return; @@ -257,8 +168,7 @@ export function checkRawPropertyIris( ): void { const isVocabularySource = (source: string | undefined): boolean => source != null && - (/^(?:jsr:|npm:)?@fedify\/vocab(?:@[^/]+)?$/.test(source) || - /^(?:jsr:|npm:)?@fedify\/fedify(?:@[^/]+)?\/vocab$/.test(source) || + (isBuiltinVocabularySource(source) || options.modules?.includes(source) === true); const scopes = new WeakMap(); const calls: Ast[] = []; diff --git a/packages/lint/src/lib/vocab-clone.ts b/packages/lint/src/lib/vocab-clone.ts new file mode 100644 index 000000000..fe6336993 --- /dev/null +++ b/packages/lint/src/lib/vocab-clone.ts @@ -0,0 +1,908 @@ +/** + * Analysis for the `vocab-clone-verifier` rule. + * + * Generated `clone()` methods of vocabulary objects do not inherit the + * source's default `verifyPortableObject`, so a `get*()` accessor called on a + * clone may dereference portable objects without verifying them. The + * analysis follows vocabulary objects through a program syntactically: it + * cannot see whether an object actually has a default verifier, so it only + * tracks which objects *may* have one. + * + * Each expression evaluates to one of these states: + * + * - `carrier`: a vocabulary object that may have a default verifier. + * - `bare`: a vocabulary object known to have none, e.g., one constructed + * without a verifier. + * - `dropped`: a `clone()` result that lost the default verifier of the + * object it was cloned from. It remembers the first `clone()` call that + * dropped the verifier, and whether a later `clone()` dropped it again. + * - `unknown`: anything else, which is never reported. + * + * A `get*()` accessor called on a `dropped` value without a verifier is + * reported at the `clone()` call that dropped it. + * @module + */ +import { + ast, + type Ast, + children, + expressionWrappers, + isVocabularySource, + name, +} from "./ast.ts"; +import type { Node } from "./types.ts"; + +/** Options of the `vocab-clone-verifier` rule. */ +export interface VocabCloneOptions { + /** + * Import specifiers of other vocabulary modules generated by + * `@fedify/vocab-tools`, in addition to `@fedify/vocab`. + */ + modules?: readonly string[]; +} + +/** A `clone()` call whose result is dereferenced without a verifier. */ +export interface VocabCloneDiagnostic { + /** The node to report: the `clone` property, or the call if computed. */ + node: Node; + /** + * Whether a later `clone()` without a verifier dropped the verifier again, + * so that fixing only this call would not help. + */ + rechained: boolean; + /** + * The `clone` identifier that a suggestion may replace with `deepClone`, + * if replacing it alone would retain the verifier. + */ + suggestionNode?: Node; +} + +type State = + | { kind: "carrier" } + | { kind: "bare" } + | { kind: "dropped"; origin: Ast; rechained: boolean } + | { kind: "unknown" }; + +const CARRIER: State = { kind: "carrier" }; +const BARE: State = { kind: "bare" }; +const UNKNOWN: State = { kind: "unknown" }; + +interface Binding { + kind: "import" | "variable" | "parameter" | "other"; + scope: Scope; + /** For imports: `"builtin"`, `"custom"`, or absent for other modules. */ + source?: "builtin" | "custom"; + imported?: string; + namespace?: boolean; + typeOnly?: boolean; + /** The initializer of a variable declared with a single identifier. */ + init?: Ast; + /** The iterated expression of a `for-of` loop declaring this variable. */ + iterated?: Ast; + /** The type annotation of a variable or parameter. */ + annotation?: Ast; + /** + * The lexical scope of the declaration, where its annotation is resolved; + * a `var` binding itself is hoisted to the function scope. + */ + declarationScope?: Scope; + /** Reassigned, redeclared, or declared by a namespace or an enum. */ + opaque?: boolean; +} + +/** The instance context of a class member. */ +interface ThisContext { + /** The class declaration or expression. */ + cls: Ast; +} + +interface Scope { + parent?: Scope; + functionScope: boolean; + bindings: Map; +} + +/** What an options argument says about `verifyPortableObject`. */ +interface OptionsInfo { + /** + * `"none"`: no verifier is passed. `"nullish"`: an explicit nullish + * `verifyPortableObject`. `"explicit"`: a verifier is, or may be, passed. + */ + verifier: "none" | "nullish" | "explicit"; + /** `dereference: false` is definitely passed. */ + noDereference: boolean; + /** `inheritPortableObjectVerifier: false` is definitely passed. */ + noInherit: boolean; +} + +const EXPLICIT_OPTIONS: OptionsInfo = { + verifier: "explicit", + noDereference: false, + noInherit: false, +}; + +const SCOPED_TYPES = new Set([ + "BlockStatement", + "CatchClause", + "ForStatement", + "ForInStatement", + "ForOfStatement", + "SwitchStatement", + "ClassExpression", + "ClassDeclaration", + "StaticBlock", +]); + +const FUNCTION_TYPES = new Set([ + "FunctionDeclaration", + "FunctionExpression", + "ArrowFunctionExpression", +]); + +const ACCESSOR_PATTERN = /^get[A-Z]/; + +function lookup(scope: Scope | undefined, id: string): Binding | undefined { + for (; scope; scope = scope.parent) { + const binding = scope.bindings.get(id); + if (binding) return binding; + } +} + +/** Strips TypeScript wrappers, parentheses, optional chains and `await`. */ +function unwrapValue(node: Ast | undefined): Ast | undefined { + while ( + node && + (expressionWrappers.has(node.type) || + node.type === "ChainExpression" || + node.type === "AwaitExpression") + ) { + node = ast( + node.type === "AwaitExpression" ? node.argument : node.expression, + ); + } + return node; +} + +/** Strips TypeScript wrappers and parentheses only. */ +function unwrapTs(node: Ast | undefined): Ast | undefined { + while (node && expressionWrappers.has(node.type)) node = ast(node.expression); + return node; +} + +/** The value of a string literal or a template literal without expressions. */ +function staticString(node: Ast | undefined): string | undefined { + if (node?.type === "Literal") { + return typeof node.value === "string" ? node.value : undefined; + } + if ( + node?.type === "TemplateLiteral" && + (node.expressions as unknown[]).length === 0 + ) { + const quasi = (node.quasis as Ast[])[0]; + const cooked = + (quasi.value as { cooked?: string } | undefined)?.cooked ?? quasi.cooked; + return typeof cooked === "string" ? cooked : undefined; + } +} + +/** The name a member expression accesses, when it is statically known. */ +function memberName(member: Ast): string | undefined { + const property = ast(member.property); + if (!member.computed) { + return property?.type === "Identifier" + ? (property.name as string) + : undefined; + } + return staticString(unwrapTs(property)); +} + +/** The source position of a node, for reporting in source order. */ +function position(node: Ast): number { + const range = node.range as [number, number] | undefined; + return range?.[0] ?? (node.start as number | undefined) ?? 0; +} + +/** + * Finds `clone()` calls on vocabulary objects whose results are dereferenced + * by `get*()` accessors without a verifier, and reports each of them once, in + * source order. + */ +export function checkVocabClones( + program: Node, + options: VocabCloneOptions, + report: (diagnostic: VocabCloneDiagnostic) => void, +): void { + const sourceKind = (source: string | undefined) => + source == null + ? undefined + : isVocabularySource(source) + ? "builtin" + : options.modules?.includes(source) + ? "custom" + : undefined; + + // Imports are top-level statements, so a file importing no vocabulary + // module has no vocabulary object to track: + const body = (program as unknown as Ast).body; + if ( + !Array.isArray(body) || + !body.some( + (statement: Ast) => + statement.type === "ImportDeclaration" && + sourceKind(name(statement.source)) != null, + ) + ) { + return; + } + + const scopes = new WeakMap(); + /** The class whose instance `this` or `super` refers to, if any. */ + const thisClasses = new WeakMap(); + const calls: Ast[] = []; + /** + * Calls inside a class member named `clone` or `deepClone`, where replacing + * `clone()` with `deepClone()` could make the override call itself. + */ + const callsInCloneOverrides = new WeakSet(); + let cloneOverrideDepth = 0; + const assignmentTargets: [Ast, Scope][] = []; + const iteratedBy = new WeakMap(); + const root: Scope = { functionScope: true, bindings: new Map() }; + + function declare(scope: Scope, id: string, binding: Binding): void { + const existing = scope.bindings.get(id); + if (existing != null) { + // A name declared twice, e.g., by two `var` declarations, may hold + // either value: + existing.opaque = true; + return; + } + scope.bindings.set(id, binding); + } + + /** Binds every identifier in a pattern as an untracked binding. */ + function bindPattern(pattern: unknown, scope: Scope): void { + const node = ast(pattern); + if (!node) return; + if (node.type === "Identifier") { + declare(scope, node.name as string, { kind: "other", scope }); + } else if (node.type === "TSParameterProperty") { + bindPattern(node.parameter, scope); + } else if (node.type === "RestElement") { + bindPattern(node.argument, scope); + } else if (node.type === "AssignmentPattern") { + bindPattern(node.left, scope); + } else if (node.type === "ObjectPattern") { + for (const property of node.properties as Ast[]) { + bindPattern( + property.type === "RestElement" ? property.argument : property.value, + scope, + ); + } + } else if (node.type === "ArrayPattern") { + for (const element of node.elements as unknown[]) { + bindPattern(element, scope); + } + } + } + + function annotationOf(node: Ast): Ast | undefined { + return ast(ast(node.typeAnnotation)?.typeAnnotation); + } + + function bindParameter(param: unknown, scope: Scope): void { + let node = ast(param); + if (node?.type === "TSParameterProperty") node = ast(node.parameter); + if (node?.type === "AssignmentPattern") node = ast(node.left); + if (node?.type === "Identifier") { + declare(scope, node.name as string, { + kind: "parameter", + scope, + annotation: annotationOf(node), + }); + } else { + bindPattern(param, scope); + } + } + + /** Collects identifiers that an assignment target writes to. */ + function collectTargets(target: unknown, scope: Scope): void { + const node = unwrapTs(ast(target)); + if (!node) return; + if (node.type === "Identifier") { + assignmentTargets.push([node, scope]); + } else if (node.type === "RestElement") { + collectTargets(node.argument, scope); + } else if (node.type === "AssignmentPattern") { + collectTargets(node.left, scope); + } else if (node.type === "ObjectPattern") { + for (const property of node.properties as Ast[]) { + collectTargets( + property.type === "RestElement" ? property.argument : property.value, + scope, + ); + } + } else if (node.type === "ArrayPattern") { + for (const element of node.elements as unknown[]) { + collectTargets(element, scope); + } + } + } + + function visitClass( + node: Ast, + outer: Scope, + thisClass: ThisContext | null, + ): void { + if (node.type === "ClassDeclaration") bindPattern(node.id, outer); + const scope: Scope = { + parent: outer, + functionScope: false, + bindings: new Map(), + }; + scopes.set(node, scope); + if (node.type === "ClassExpression") bindPattern(node.id, scope); + // The superclass and decorators are evaluated outside the class body: + const superClass = ast(node.superClass); + if (superClass) visit(superClass, outer, thisClass); + for (const decorator of (node.decorators as unknown[] | undefined) ?? []) { + const child = ast(decorator); + if (child) visit(child, outer, thisClass); + } + const classBody = ast(node.body); + if (!classBody) return; + scopes.set(classBody, scope); + for (const member of classBody.body as Ast[]) { + scopes.set(member, scope); + const key = ast(member.key); + if (key && member.computed) visit(key, scope, thisClass); + for (const decorator of (member.decorators as unknown[] | undefined) ?? + []) { + const child = ast(decorator); + if (child) visit(child, scope, thisClass); + } + const instance: ThisContext | null = member.static ? null : { cls: node }; + const memberName = member.computed + ? staticString(unwrapTs(key)) + : name(key); + const override = memberName === "clone" || memberName === "deepClone"; + if (override) cloneOverrideDepth++; + if (member.type === "MethodDefinition") { + const value = ast(member.value); + if (value) visitFunction(value, scope, instance); + } else if ( + member.type === "PropertyDefinition" || + member.type === "AccessorProperty" + ) { + const value = ast(member.value); + if (value) visit(value, scope, instance); + } else if (member.type === "StaticBlock") { + visit(member, scope, null); + } else { + // Index signatures and other type-only members: + for (const child of children(member)) visit(child, scope, null); + } + if (override) cloneOverrideDepth--; + } + } + + function visitFunction( + node: Ast, + outer: Scope, + thisClass: ThisContext | null, + ): void { + if (node.type === "FunctionDeclaration") bindPattern(node.id, outer); + const scope: Scope = { + parent: outer, + functionScope: true, + bindings: new Map(), + }; + scopes.set(node, scope); + if (node.type === "FunctionExpression") bindPattern(node.id, scope); + for (const param of node.params as unknown[]) bindParameter(param, scope); + for (const child of children(node)) { + if (child === node.id) continue; + visit(child, scope, thisClass); + } + } + + function visit(node: Ast, outer: Scope, thisClass: ThisContext | null): void { + if ( + node.type === "TSModuleDeclaration" || + node.type === "TSEnumDeclaration" + ) { + // Keep the enclosing binding opaque, including the first segment of a + // dotted namespace name, and skip the body, as declaration merging can + // make names in it refer to other values: + let id = ast(node.id); + while (id?.type === "TSQualifiedName") id = ast(id.left); + if (id?.type === "Identifier") { + declare(outer, id.name as string, { + kind: "other", + scope: outer, + opaque: true, + }); + } + return; + } + if (node.type === "TSModuleBlock") return; + if (node.type === "ClassDeclaration" || node.type === "ClassExpression") { + visitClass(node, outer, thisClass); + return; + } + if (FUNCTION_TYPES.has(node.type)) { + // Only arrow functions keep the enclosing `this`: + visitFunction( + node, + outer, + node.type === "ArrowFunctionExpression" ? thisClass : null, + ); + return; + } + const scope: Scope = SCOPED_TYPES.has(node.type) + ? { + parent: outer, + functionScope: node.type === "StaticBlock", + bindings: new Map(), + } + : outer; + scopes.set(node, scope); + switch (node.type) { + case "ThisExpression": + case "Super": + thisClasses.set(node, thisClass); + break; + case "CallExpression": + calls.push(node); + if (cloneOverrideDepth > 0) callsInCloneOverrides.add(node); + break; + case "CatchClause": + bindPattern(node.param, scope); + break; + case "TSImportEqualsDeclaration": + bindPattern(node.id, scope); + break; + case "ImportDeclaration": { + const source = sourceKind(name(node.source)); + for (const specifier of node.specifiers as Ast[]) { + const local = ast(specifier.local); + if (local?.type !== "Identifier") continue; + // Vocabulary modules have no default export: + const tracked = + source != null && specifier.type !== "ImportDefaultSpecifier"; + declare(scope, local.name as string, { + kind: tracked ? "import" : "other", + scope, + source, + imported: name(specifier.imported), + namespace: specifier.type === "ImportNamespaceSpecifier", + typeOnly: + node.importKind === "type" || specifier.importKind === "type", + }); + } + break; + } + case "VariableDeclaration": { + let target = scope; + if (node.kind === "var") { + while (!target.functionScope && target.parent) target = target.parent; + } + const declarations = node.declarations as Ast[]; + const iterated = iteratedBy.get(node); + for (const declaration of declarations) { + const id = ast(declaration.id); + if (id?.type === "Identifier") { + declare(target, id.name as string, { + kind: "variable", + scope: target, + init: ast(declaration.init), + iterated: declarations.length === 1 ? iterated : undefined, + annotation: annotationOf(id), + declarationScope: scope, + }); + } else { + bindPattern(declaration.id, target); + } + } + break; + } + case "AssignmentExpression": + collectTargets(node.left, scope); + break; + case "UpdateExpression": + collectTargets(node.argument, scope); + break; + case "ForInStatement": + case "ForOfStatement": { + const left = ast(node.left); + if (left?.type === "VariableDeclaration") { + if (node.type === "ForOfStatement") { + const right = ast(node.right); + if (right) iteratedBy.set(left, right); + } + } else { + collectTargets(left, scope); + } + break; + } + } + // ESTree providers also walk type annotations here, through enumerable + // keys, while Deno does not; nothing below may depend on either, as no + // call or binding the analysis tracks lives in a type position. + for (const child of children(node)) { + // The discriminant of a switch is evaluated outside its case scope: + visit( + child, + node.type === "SwitchStatement" && child === node.discriminant + ? outer + : scope, + thisClass, + ); + } + } + + visit(program as unknown as Ast, root, null); + + for (const [target, scope] of assignmentTargets) { + const binding = lookup(scope, target.name as string); + if (binding) binding.opaque = true; + } + + const isUndefined = (node: Ast): boolean => + node.type === "Identifier" && + node.name === "undefined" && + lookup(scopes.get(node), "undefined") == null; + + const isVoid = (node: Ast): boolean => + node.type === "UnaryExpression" && node.operator === "void"; + + const isNullLiteral = (node: Ast): boolean => + node.type === "Literal" && node.value === null && node.raw === "null"; + + /** The import binding an identifier refers to, if any. */ + function importOf(node: Ast | undefined): Binding | undefined { + if (node?.type !== "Identifier") return; + const binding = lookup(scopes.get(node), node.name as string); + return binding?.kind === "import" && !binding.opaque ? binding : undefined; + } + + /** Whether an expression refers to a value export of a vocabulary module. */ + function isVocabularyValue(node: Ast | undefined): boolean { + node = unwrapTs(node); + if (node?.type === "Identifier") { + const binding = importOf(node); + return ( + binding != null && + !binding.typeOnly && + !binding.namespace && + binding.imported !== "lookupObject" + ); + } + if (node?.type === "MemberExpression") { + const binding = importOf(unwrapTs(ast(node.object))); + return ( + binding != null && + binding.namespace === true && + !binding.typeOnly && + memberName(node) != null && + memberName(node) !== "lookupObject" + ); + } + return false; + } + + /** Whether a callee is `lookupObject()` from the built-in module. */ + function isLookupObject(callee: Ast | undefined): boolean { + callee = unwrapTs(callee); + if (callee?.type === "Identifier") { + const binding = importOf(callee); + return ( + binding?.source === "builtin" && + !binding.typeOnly && + !binding.namespace && + binding.imported === "lookupObject" + ); + } + if (callee?.type === "MemberExpression") { + const binding = importOf(unwrapTs(ast(callee.object))); + return ( + binding?.source === "builtin" && + binding.namespace === true && + !binding.typeOnly && + memberName(callee) === "lookupObject" + ); + } + return false; + } + + /** + * Classifies a type annotation: `"vocab"` for a vocabulary type, possibly + * in a union with `null` or `undefined`, `"nullish"` for `null` or + * `undefined` alone, and `"other"` for anything else. + */ + function typeKind( + node: Ast | undefined, + scope: Scope, + ): "vocab" | "nullish" | "other" { + while (node?.type === "TSParenthesizedType") { + node = ast(node.typeAnnotation); + } + if (!node) return "other"; + if ( + node.type === "TSNullKeyword" || + node.type === "TSUndefinedKeyword" || + (node.type === "TSLiteralType" && + isNullLiteral(ast(node.literal) ?? node)) + ) { + return "nullish"; + } + if (node.type === "TSUnionType") { + let vocab = false; + for (const member of node.types as Ast[]) { + const kind = typeKind(member, scope); + if (kind === "other") return "other"; + if (kind === "vocab") vocab = true; + } + return vocab ? "vocab" : "nullish"; + } + if (node.type !== "TSTypeReference") return "other"; + if ((node.typeArguments ?? node.typeParameters) != null) return "other"; + const typeName = ast(node.typeName); + let id: Ast | undefined; + let qualified = false; + if (typeName?.type === "Identifier") { + id = typeName; + } else if (typeName?.type === "TSQualifiedName") { + id = ast(typeName.left); + qualified = true; + } + if (id?.type !== "Identifier") return "other"; + const binding = lookup(scope, id.name as string); + if (binding?.kind !== "import" || binding.opaque) return "other"; + return binding.namespace === qualified ? "vocab" : "other"; + } + + /** Analyzes an options argument, as described in {@link OptionsInfo}. */ + function optionsAt(args: Ast[], index: number): OptionsInfo { + for (let i = 0; i <= index && i < args.length; i++) { + if (args[i].type === "SpreadElement") return EXPLICIT_OPTIONS; + } + const arg = unwrapTs(args[index]); + if (arg == null || isUndefined(arg) || isVoid(arg)) { + return { verifier: "none", noDereference: false, noInherit: false }; + } + if (arg.type !== "ObjectExpression") return EXPLICIT_OPTIONS; + // The last definite value of each key; `null` marks a key that something + // unknown, such as a spread, may have overwritten: + const values = new Map(); + let unknownRest = false; + const keys = [ + "verifyPortableObject", + "dereference", + "inheritPortableObjectVerifier", + ]; + const invalidate = () => { + unknownRest = true; + for (const key of keys) values.set(key, null); + }; + for (const property of arg.properties as Ast[]) { + if (property.type !== "Property") { + invalidate(); + continue; + } + const keyNode = ast(property.key); + let key: string | undefined; + if (property.computed) { + key = staticString(unwrapTs(keyNode)); + if (key == null) { + invalidate(); + continue; + } + } else if (keyNode?.type === "Identifier") { + key = keyNode.name as string; + } else { + key = staticString(keyNode); + } + if ( + key === "__proto__" && + !property.computed && + !property.shorthand && + !property.method && + property.kind === "init" + ) { + // This sets the prototype, which may supply any option: + invalidate(); + continue; + } + if (key == null || !keys.includes(key)) continue; + // Accessors and methods supply a value that is not statically known: + values.set( + key, + property.kind === "init" && !property.method + ? (unwrapTs(ast(property.value)) ?? null) + : null, + ); + } + const verifierValue = values.get("verifyPortableObject"); + let verifier: OptionsInfo["verifier"]; + if (verifierValue === undefined) { + verifier = unknownRest ? "explicit" : "none"; + } else if (verifierValue === null) { + verifier = "explicit"; + } else { + verifier = + isUndefined(verifierValue) || + isVoid(verifierValue) || + isNullLiteral(verifierValue) + ? "nullish" + : "explicit"; + } + const isFalse = (key: string): boolean => { + const value = values.get(key); + return value != null && value.type === "Literal" && value.value === false; + }; + return { + verifier, + noDereference: isFalse("dereference"), + noInherit: isFalse("inheritPortableObjectVerifier"), + }; + } + + const states = new Map(); + const bindingStates = new Map(); + const inProgress = new Set(); + /** Offending `clone()` calls, and whether any path re-cloned them. */ + const offenders = new Map(); + + function bindingState(binding: Binding): State { + if (binding.opaque) return UNKNOWN; + const known = bindingStates.get(binding); + if (known) return known; + // A cyclic alias, such as `var a = b; var b = a;`, holds no known value: + if (inProgress.has(binding)) return UNKNOWN; + inProgress.add(binding); + let state = UNKNOWN; + if (binding.kind === "variable") { + if (binding.init) state = evaluate(binding.init); + if (state.kind === "unknown" && binding.iterated) { + const iterated = unwrapValue(binding.iterated); + if (iterated?.type === "CallExpression" && isAccessorCall(iterated)) { + state = evaluate(iterated); + } + } + } + if ( + state.kind === "unknown" && + (binding.kind === "variable" || binding.kind === "parameter") && + binding.annotation && + typeKind( + binding.annotation, + binding.declarationScope ?? binding.scope, + ) === "vocab" + ) { + state = CARRIER; + } + inProgress.delete(binding); + bindingStates.set(binding, state); + return state; + } + + function isAccessorCall(call: Ast): boolean { + const callee = unwrapValue(ast(call.callee)); + if (callee?.type !== "MemberExpression") return false; + const method = memberName(callee); + return method != null && ACCESSOR_PATTERN.test(method); + } + + function evaluate(expression: Ast): State { + const node = unwrapValue(expression); + if (!node) return UNKNOWN; + const known = states.get(node); + if (known) return known; + if (inProgress.has(node)) return UNKNOWN; + inProgress.add(node); + const state = evaluateNode(node); + inProgress.delete(node); + states.set(node, state); + return state; + } + + function evaluateNode(node: Ast): State { + switch (node.type) { + case "Identifier": { + const binding = lookup(scopes.get(node), node.name as string); + return binding ? bindingState(binding) : UNKNOWN; + } + case "ThisExpression": + case "Super": { + const context = thisClasses.get(node); + return context != null && isVocabularyValue(ast(context.cls.superClass)) + ? CARRIER + : UNKNOWN; + } + case "NewExpression": + if (!isVocabularyValue(ast(node.callee))) return UNKNOWN; + return optionsAt(node.arguments as Ast[], 1).verifier === "explicit" + ? CARRIER + : BARE; + case "CallExpression": + return evaluateCall(node); + default: + return UNKNOWN; + } + } + + function evaluateCall(call: Ast): State { + const args = call.arguments as Ast[]; + const rawCallee = ast(call.callee); + if (isLookupObject(unwrapValue(rawCallee))) { + return optionsAt(args, 1).verifier === "explicit" ? CARRIER : BARE; + } + const callee = unwrapValue(rawCallee); + if (callee?.type !== "MemberExpression") return UNKNOWN; + const method = memberName(callee); + if (method == null) return UNKNOWN; + const object = ast(callee.object); + if (method === "fromJsonLd" && isVocabularyValue(unwrapValue(object))) { + return optionsAt(args, 1).verifier === "explicit" ? CARRIER : BARE; + } + const isClone = method === "clone"; + const isDeepClone = method === "deepClone"; + const isAccessor = ACCESSOR_PATTERN.test(method); + if (!isClone && !isDeepClone && !isAccessor) return UNKNOWN; + const receiver = object ? evaluate(object) : UNKNOWN; + if (receiver.kind === "unknown") return UNKNOWN; + if (isClone) { + const { verifier } = optionsAt(args, 1); + if (verifier === "explicit") return CARRIER; + if (verifier === "nullish" || receiver.kind === "bare") return BARE; + return receiver.kind === "dropped" + ? { kind: "dropped", origin: receiver.origin, rechained: true } + : { kind: "dropped", origin: call, rechained: false }; + } + if (isDeepClone) { + // deepClone() falls back to the receiver's own default: + if (receiver.kind === "carrier") return CARRIER; + return optionsAt(args, 1).verifier === "explicit" ? CARRIER : receiver; + } + const info = optionsAt(args, 0); + if ( + receiver.kind === "dropped" && + info.verifier === "none" && + !info.noDereference + ) { + offenders.set( + receiver.origin, + (offenders.get(receiver.origin) ?? false) || receiver.rechained, + ); + } + if (receiver.kind === "carrier") return CARRIER; + return info.verifier === "explicit" && + !info.noInherit && + !info.noDereference + ? CARRIER + : UNKNOWN; + } + + for (const call of calls) evaluate(call); + + const sorted = [...offenders].sort(([a], [b]) => position(a) - position(b)); + for (const [call, rechained] of sorted) { + const callee = unwrapValue(ast(call.callee))!; + const property = ast(callee.property)!; + // Inside a clone() or deepClone() override, deepClone() could end up + // calling the override again, which would call deepClone() again: + const recursive = callsInCloneOverrides.has(call); + report({ + node: (callee.computed ? call : property) as unknown as Node, + rechained, + suggestionNode: + !rechained && + !recursive && + !callee.computed && + property.type === "Identifier" + ? (property as unknown as Node) + : undefined, + }); + } +} diff --git a/packages/lint/src/mod.ts b/packages/lint/src/mod.ts index 05a9b192b..86bd420cb 100644 --- a/packages/lint/src/mod.ts +++ b/packages/lint/src/mod.ts @@ -32,9 +32,10 @@ import { deno as outboxListenerDeliveryRequired } from "./rules/outbox-listener- import { deno as rawPropertyIriInvalid } from "./rules/raw-property-iri-invalid.ts"; -// `outbox-listener-delivery-not-awaited` is deliberately not registered here: -// Deno turns on every rule of a plugin as soon as the plugin is listed, and -// gives the rule no way to stay off until a project asks for it. +// `outbox-listener-delivery-not-awaited` and `vocab-clone-verifier` are +// deliberately not registered here: Deno turns on every rule of a plugin as +// soon as the plugin is listed, reports every plugin rule as an error, and +// gives these heuristic rules no way to stay off until a project asks for it. const plugin: Deno.lint.Plugin = { name: "fedify-lint", rules: { diff --git a/packages/lint/src/oxlint.ts b/packages/lint/src/oxlint.ts index b19b7b605..fa4adbc1d 100644 --- a/packages/lint/src/oxlint.ts +++ b/packages/lint/src/oxlint.ts @@ -51,6 +51,7 @@ import { eslint as outboxListenerDeliveryNotAwaited } from "./rules/outbox-liste import { eslint as outboxListenerDeliveryRequired } from "./rules/outbox-listener-delivery-required.ts"; import { eslint as rawPropertyIriInvalid } from "./rules/raw-property-iri-invalid.ts"; +import { eslint as vocabCloneVerifier } from "./rules/vocab-clone-verifier.ts"; const rules: Record<(typeof RULE_IDS)[keyof typeof RULE_IDS], Rule.RuleModule> = { @@ -94,6 +95,7 @@ const rules: Record<(typeof RULE_IDS)[keyof typeof RULE_IDS], Rule.RuleModule> = mediaUploaderAuthorizationRequired, [RULE_IDS.denoKvStoreDeprecated]: denoKvStoreDeprecated, [RULE_IDS.denoKvMessageQueueDeprecated]: denoKvMessageQueueDeprecated, + [RULE_IDS.vocabCloneVerifier]: vocabCloneVerifier, }; /** diff --git a/packages/lint/src/rules/vocab-clone-verifier.ts b/packages/lint/src/rules/vocab-clone-verifier.ts new file mode 100644 index 000000000..566719324 --- /dev/null +++ b/packages/lint/src/rules/vocab-clone-verifier.ts @@ -0,0 +1,75 @@ +import type { Rule } from "eslint"; +import { VOCAB_CLONE_VERIFIER_MESSAGES } from "../lib/messages.ts"; +import { + checkVocabClones, + type VocabCloneOptions, +} from "../lib/vocab-clone.ts"; + +/** + * Deno Lint adapter. It is not registered in the Deno plugin, since Deno + * enables every rule of a plugin and reports them all as errors, but it can be + * wired up by hand. Deno has no suggestion API, so it only reports. + */ +export const deno: Deno.lint.Rule = { + create(context) { + return { + Program(node) { + checkVocabClones(node, {}, ({ node, rechained }) => { + context.report({ + node: node as Deno.lint.Node, + message: rechained + ? VOCAB_CLONE_VERIFIER_MESSAGES.dropsVerifierRechained + : VOCAB_CLONE_VERIFIER_MESSAGES.dropsVerifier, + }); + }); + }, + }; + }, +}; + +/** ESLint and Oxlint adapter, with optional generated vocabulary modules. */ +export const eslint: Rule.RuleModule = { + meta: { + type: "suggestion", + docs: { + description: + "Warn when a clone of a vocabulary object, which does not inherit its default portable-object verifier, is dereferenced without one", + }, + hasSuggestions: true, + messages: VOCAB_CLONE_VERIFIER_MESSAGES, + schema: [ + { + type: "object", + properties: { modules: { type: "array", items: { type: "string" } } }, + additionalProperties: false, + }, + ], + }, + create(context) { + const options: VocabCloneOptions = context.options[0] ?? {}; + return { + Program(node) { + checkVocabClones(node, options, (diagnostic) => { + const { node, rechained, suggestionNode } = diagnostic; + context.report({ + node: node as Rule.Node, + messageId: rechained ? "dropsVerifierRechained" : "dropsVerifier", + suggest: + suggestionNode == null + ? [] + : [ + { + messageId: "useDeepClone", + fix: (fixer) => + fixer.replaceText( + suggestionNode as Rule.Node, + "deepClone", + ), + }, + ], + }); + }); + }, + }; + }, +}; diff --git a/packages/lint/src/tests/vocab-clone-verifier.registration.test.ts b/packages/lint/src/tests/vocab-clone-verifier.registration.test.ts new file mode 100644 index 000000000..b22c35f20 --- /dev/null +++ b/packages/lint/src/tests/vocab-clone-verifier.registration.test.ts @@ -0,0 +1,23 @@ +import { deepStrictEqual, ok } from "node:assert/strict"; +import { test } from "node:test"; +import { plugin } from "../index.ts"; +import { RULE_IDS } from "../lib/const.ts"; +import denoPlugin from "../mod.ts"; +import oxlintPlugin from "../oxlint.ts"; + +const ruleId = RULE_IDS.vocabCloneVerifier; +const eslintRuleId = `@fedify/lint/${ruleId}`; + +test(`${ruleId}: registered for ESLint, as a warning in recommended and an error in strict`, () => { + ok(plugin.rules != null && ruleId in plugin.rules); + deepStrictEqual(plugin.configs.recommended.rules[eslintRuleId], "warn"); + deepStrictEqual(plugin.configs.strict.rules[eslintRuleId], "error"); +}); + +test(`${ruleId}: registered for Oxlint`, () => { + ok(ruleId in oxlintPlugin.rules); +}); + +test(`${ruleId}: not registered for Deno, which enables every rule of a plugin`, () => { + ok(!(ruleId in denoPlugin.rules)); +}); diff --git a/packages/lint/src/tests/vocab-clone-verifier.test.ts b/packages/lint/src/tests/vocab-clone-verifier.test.ts new file mode 100644 index 000000000..06b4715e5 --- /dev/null +++ b/packages/lint/src/tests/vocab-clone-verifier.test.ts @@ -0,0 +1,680 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import * as parser from "@typescript-eslint/parser"; +import { Linter } from "eslint"; +import { oxlintUnavailable, runOxlint } from "../lib/oxlint.ts"; +import lintTest from "../lib/test.ts"; +import * as rule from "../rules/vocab-clone-verifier.ts"; + +const ruleName = "vocab-clone-verifier"; +const reported = "does not inherit"; +const imports = + 'import { Article, Collection, Create, Note, Object as APObject, lookupObject } from "@fedify/vocab";\n'; + +/** `[label, code, expected?]`; with `expected`, the rule must report. */ +const cases: [string, string, string?][] = [ + // The pattern fixed in #1396: + [ + "backfill shape", + `${imports}async function f(note: Note) { + return await note.clone().getContextHistory({ + crossOrigin: "trust", + documentLoader: (url) => fetch(url), + }); + }`, + reported, + ], + [ + "aliased Object parameter", + `${imports}async function f(note: APObject) { + return await note.clone().getContextHistory({ crossOrigin: "trust" }); + }`, + reported, + ], + [ + "same-scope variable", + `${imports}async function f(note: Note) { + const copy = note.clone(); + return await copy.getContextHistory({ crossOrigin: "trust" }); + }`, + reported, + ], + [ + "alias of a clone", + `${imports}async function f(note: Note) { + const copy = note.clone({ content: "x" }); + const other = copy; + await other.getAttribution(); + }`, + reported, + ], + [ + "type-only import", + `import type { Note } from "@fedify/vocab"; + async function f(note: Note) { await note.clone().getObject(); }`, + reported, + ], + [ + "type-only specifier", + `import { type Note } from "@fedify/vocab"; + async function f(note: Note) { await note.clone().getObject(); }`, + reported, + ], + [ + "namespace type annotation", + `import * as vocab from "@fedify/vocab"; + async function f(note: vocab.Note) { await note.clone().getObject(); }`, + reported, + ], + [ + "@fedify/fedify/vocab", + `import { Note } from "@fedify/fedify/vocab"; + async function f(note: Note) { await note.clone().getObject(); }`, + reported, + ], + [ + "versioned jsr specifier", + `import { Note } from "jsr:@fedify/vocab@^2.5.0"; + async function f(note: Note) { await note.clone().getObject(); }`, + reported, + ], + [ + "nullable union", + `${imports}async function f(note: Note | null) { await note?.clone().getObject(); }`, + reported, + ], + [ + "parenthesized union", + `${imports}async function f(note: (Note | Article) | undefined) { await note!.clone().getObject(); }`, + reported, + ], + [ + "optional chaining", + `${imports}async function f(note?: Note) { await note?.clone()?.getObject?.(); }`, + reported, + ], + [ + "casts", + `${imports}async function f(note: Note) { + await (note as Note).clone().getObject(); + await (note!.clone() satisfies Note).getObject(); + }`, + reported, + ], + [ + "default parameter", + `${imports}async function f(note: Note = new Note({})) { await note.clone().getObject(); }`, + reported, + ], + [ + "parameter property", + `${imports}class C { constructor(private readonly note: Note) {} } + async function f(note: Note) { await note.clone().getObject(); }`, + reported, + ], + [ + "annotated clone variable", + `${imports}async function f(note: Note) { + const copy: Note = note.clone(); + await copy.getObject(); + }`, + reported, + ], + [ + "constructor with a verifier", + `${imports}async function f(verifyPortableObject: never) { + const note = new Note({}, { verifyPortableObject }); + await note.clone().getObject(); + }`, + reported, + ], + [ + "constructor with a context", + `${imports}import * as vocab from "@fedify/vocab"; + async function f(ctx: unknown) { + const note = new vocab.Note({}, ctx as never); + await note.clone().getObject(); + }`, + reported, + ], + [ + "fromJsonLd with options", + `${imports}async function f(doc: unknown, ctx: never) { + const note = await Note.fromJsonLd(doc, ctx); + await note.clone().getObject(); + }`, + reported, + ], + [ + "lookupObject with options", + `${imports}async function f(ctx: never) { + const object = await lookupObject("https://example.com/", ctx); + await object?.clone().getAttribution(); + }`, + reported, + ], + [ + "this in a subclass", + `${imports}class MyNote extends Note { + async history() { return await this.clone().getContextHistory(); } + }`, + reported, + ], + [ + "arrow field in a subclass", + `${imports}class MyNote extends Note { + history = () => this.clone().getContextHistory(); + }`, + reported, + ], + [ + "super in a subclass", + `${imports}class MyNote extends Note { + async history() { return await super.clone().getContextHistory(); } + }`, + reported, + ], + [ + "accessor result", + `${imports}async function f(create: Create) { + const object = await create.getObject(); + await object?.clone().getAttribution(); + }`, + reported, + ], + [ + "for-await binding", + `${imports}async function f(create: Create) { + for await (const object of create.getObjects()) { + await object.clone().getAttribution(); + } + }`, + reported, + ], + [ + "unconsumed plural accessor", + `${imports}async function f(note: Note) { + for await (const _ of note.clone().getAttachments()) break; + }`, + reported, + ], + [ + "deepClone after clone", + `${imports}async function f(note: Note) { await note.clone().deepClone().getObject(); }`, + reported, + ], + [ + "deepClone with nullish verifier after clone", + `${imports}async function f(note: Note) { + await note.clone().deepClone({}, { verifyPortableObject: undefined }).getObject(); + await note.clone().deepClone({}, { verifyPortableObject: null }).getObject(); + }`, + reported, + ], + [ + "clone of a clone", + `${imports}async function f(note: Note) { await note.clone().clone().getObject(); }`, + "a later `clone()` in the chain", + ], + [ + "computed clone", + `${imports}async function f(note: Note) { await note["clone"]()[\`getObject\`](); }`, + reported, + ], + [ + "explicit undefined options", + `${imports}async function f(note: Note) { + await note.clone({}, undefined).getObject(undefined); + await note.clone({}, void 0).getObject(); + }`, + reported, + ], + [ + "options without a verifier", + `${imports}async function f(note: Note, loader: never) { + await note.clone({}, { documentLoader: loader }).getObject({ documentLoader: loader }); + }`, + reported, + ], + [ + "last dereference option wins", + `${imports}async function f(note: Note) { + await note.clone().getObject({ dereference: false, dereference: true }); + }`, + reported, + ], + [ + "earlier spread may supply a verifier", + `${imports}async function f(note: Note, base: never) { + await note.clone().getObject({ ...base, documentLoader: base }); + }`, + ], + [ + "closure over an outer clone", + `${imports}function f(note: Note) { + const copy = note.clone(); + return async () => await copy.getObject(); + }`, + reported, + ], + [ + "block-local function does not shadow outside the block", + `${imports}async function f(note: Note) { + { function Note() {} } + await note.clone().getObject(); + }`, + reported, + ], + [ + "inheriting accessor result", + `${imports}async function f(note: Note, ctx: never) { + const object = await note.clone().getObject(ctx); + await object?.clone().getAttribution(); + }`, + reported, + ], + + // Negative cases: + [ + "Request, Response, and Router clones", + `${imports}async function f(request: Request, response: Response, router: { clone(): { getRoute(): void } }) { + await request.clone().text(); + await response.clone().json(); + router.clone().getRoute(); + }`, + ], + [ + "Context clone", + `import type { Context } from "@fedify/fedify"; + ${imports}async function f(ctx: Context) { (ctx as any).clone().getActorUri("x"); }`, + ], + [ + "deepClone", + `${imports}async function f(note: Note) { await note.deepClone().getContextHistory(); }`, + ], + [ + "clone with a verifier", + `${imports}async function f(note: Note, verifyPortableObject: never) { + await note.clone({}, { verifyPortableObject }).getObject(); + await note.clone({}, { verifyPortableObject: verifyPortableObject }).getObject(); + }`, + ], + [ + "clone with a context", + `${imports}async function f(note: Note, ctx: never) { await note.clone({}, ctx).getObject(); }`, + ], + [ + "clone with an explicit nullish verifier", + `${imports}async function f(note: Note) { + await note.clone({}, { verifyPortableObject: undefined }).getObject(); + }`, + ], + [ + "accessor with a verifier", + `${imports}async function f(note: Note, ctx: never, verifyPortableObject: never) { + await note.clone().getObject(ctx); + await note.clone().getObject({ verifyPortableObject }); + await note.clone().getObject({ verifyPortableObject: undefined }); + }`, + ], + [ + "accessor without dereferencing", + `${imports}async function f(note: Note) { + await note.clone().getObject({ dereference: false }); + }`, + ], + [ + "unknown computed key", + `${imports}async function f(note: Note, k: string) { + await note.clone().getObject({ dereference: false, [k]: true }); + }`, + ], + [ + "spread options", + `${imports}async function f(note: Note, args: never[], base: never) { + await note.clone(...args).getObject(); + await note.clone().getObject({ verifyPortableObject: undefined, ...base }); + await note.clone({}, { ...base }).getObject(); + }`, + ], + [ + "shadowed undefined", + `${imports}async function f(note: Note, undefined: never) { + await note.clone({}, undefined).getObject(); + }`, + ], + [ + "locally constructed objects", + `${imports}async function f(doc: unknown) { + await new Note({}).clone().getObject(); + await new Note({}, {}).clone().getObject(); + const note: Note = new Note({ content: "x" }); + await note.clone().getObject(); + const parsed: APObject = await Note.fromJsonLd(doc, {}); + await parsed.clone().getObject(); + await (await Note.fromJsonLd(doc)).clone().getObject(); + const found = await lookupObject("https://example.com/"); + await found?.clone().getObject(); + }`, + ], + [ + "type-only import cannot construct", + `import type { Note } from "@fedify/vocab"; + async function f(ctx: never) { await new (Note as any)({}, ctx).clone().getObject(); }`, + ], + [ + "serialized clones", + `${imports}async function f(note: Note) { + const copy = note.clone({ content: "x" }); + return await copy.toJsonLd(); + }`, + ], + [ + "shadowed import", + `${imports}async function f(Note: any, note: Note) {} + async function g(note: Note) { + const Note = 1; + await new Note({}, {} as never).clone().getObject(); + }`, + ], + [ + "no vocabulary import", + `class Note { clone() { return this; } async getObject() {} } + async function f(note: Note) { await note.clone().getObject(); }`, + ], + [ + "other module", + `import { Note } from "other-vocab"; + async function f(note: Note) { await note.clone().getObject(); }`, + ], + [ + "reassigned variable", + `${imports}async function f(note: Note) { + let copy = note.clone(); + copy = note.deepClone(); + await copy.getObject(); + }`, + ], + [ + "destructuring reassignments", + `${imports}async function f(note: Note, o: never, items: never[]) { + let a = note.clone(); + let b = note.clone(); + let c = note.clone(); + ({ a } = o); + ({ x: b } = o); + for ([c] of items); + await a.getObject(); + await b.getObject(); + await c.getObject(); + }`, + ], + [ + "untyped parameter", + `${imports}async function f(note) { await note.clone().getObject(); }`, + ], + [ + "static this", + `${imports}class MyNote extends Note { + static async history() { return await this.clone().getContextHistory(); } + }`, + ], + [ + "nested function this", + `${imports}class MyNote extends Note { + async history() { + return function (this: any) { return this.clone().getContextHistory(); }; + } + field = function (this: any) { return this.clone().getObject(); }; + }`, + ], + [ + "class not extending a vocabulary type", + `${imports}class Plain { async history() { return await (this as any).clone().getObject(); } }`, + ], + [ + "cyclic aliases", + `${imports}async function f() { + var a = b; + var b = a; + await a.clone().getObject(); + }`, + ], + [ + "non-vocabulary annotations", + `${imports}async function f(a: null | undefined, b: Promise, c: Note[]) { + await (a as any).clone().getObject(); + await (b as any).clone().getObject(); + await (c as any).clone().getObject(); + }`, + ], + [ + "accessor result that does not inherit", + `${imports}async function f(note: Note, verifyPortableObject: never) { + const a = await note.clone({}, { verifyPortableObject: undefined }).getObject({ + verifyPortableObject, + inheritPortableObjectVerifier: false, + }); + await a?.clone().getObject(); + }`, + ], + [ + "deepClone of a clone with a verifier", + `${imports}async function f(note: Note, ctx: never) { + await note.clone().deepClone({}, ctx).getObject(); + }`, + ], + [ + "var annotation resolved in its block", + `${imports}async function f() { + { + class Note { clone() { return this; } async getObject() {} } + var value: Note = new Note(); + await value.clone().getObject(); + } + }`, + ], + [ + "default import", + `import vocab from "@fedify/vocab"; + async function f(note: vocab) { await (note as any).clone().getObject(); }`, + ], + [ + "namespace bodies are ignored", + `${imports}namespace N { export async function f(note: Note) { await note.clone().getObject(); } }`, + ], +]; + +for (const [label, code, expectedError] of cases) { + test( + `${ruleName}: ${label}`, + lintTest({ rule, ruleName, code, federationSetup: "", expectedError }), + ); +} + +function verify(code: string, options: { modules?: string[] } = {}) { + return new Linter().verify( + code, + [ + { + files: ["**/*.ts"], + languageOptions: { parser }, + plugins: { fedify: { rules: { [ruleName]: rule.eslint } } }, + rules: { [`fedify/${ruleName}`]: ["warn", options] }, + }, + ], + "test.ts", + ); +} + +function applySuggestion(code: string, message: Linter.LintMessage): string { + const { fix } = message.suggestions![0]; + return code.slice(0, fix.range[0]) + fix.text + code.slice(fix.range[1]); +} + +test("ESLint: reports once per clone, at the clone property", () => { + const code = `${imports}async function f(note: Note) { + const copy = note.clone(); + await copy.getObject(); + await copy.getAttribution(); +}`; + const messages = verify(code); + assert.equal(messages.length, 1); + assert.equal(messages[0].messageId, "dropsVerifier"); + assert.equal(messages[0].line, 3); + assert.equal(messages[0].column, 21); + assert.equal(messages[0].endColumn, 26); +}); + +test("ESLint: reports separate clones in source order", () => { + const code = `${imports}async function f(note: Note, other: Note) { + const b = other.clone(); + await note.clone().getObject(); + await b.getObject(); +}`; + const messages = verify(code); + assert.deepEqual( + messages.map((m) => m.line), + [3, 4], + ); +}); + +test("ESLint: suggests deepClone(), never autofixes", () => { + const code = `${imports}async function f(note: Note) { + await note.clone().getContextHistory({ crossOrigin: "trust" }); +}`; + const [message] = verify(code); + assert.equal(message.fix, undefined); + assert.equal(message.suggestions?.length, 1); + assert.equal(message.suggestions![0].messageId, "useDeepClone"); + const fixed = applySuggestion(code, message); + assert.ok(fixed.includes("note.deepClone().getContextHistory(")); + assert.equal(verify(fixed).length, 0); +}); + +test("ESLint: no suggestion for computed clones", () => { + const [message] = verify( + `${imports}async function f(note: Note) { await note["clone"]().getObject(); }`, + ); + assert.equal(message.messageId, "dropsVerifier"); + assert.equal(message.suggestions, undefined); +}); + +test("ESLint: no suggestion for this.clone() inside a clone() override", () => { + const code = `${imports}class MyNote extends Note { + override clone(values = {}, options = {}) { + void this.clone().getObject(); + return super.clone(values, options); + } +}`; + const [message] = verify(code); + assert.equal(message.messageId, "dropsVerifier"); + assert.equal(message.suggestions, undefined); +}); + +test("ESLint: no suggestion inside super.clone(), computed clone(), or deepClone() overrides", () => { + for (const code of [ + `${imports}class MyNote extends Note { + override clone(values = {}, options = {}) { + void super.clone().getObject(); + return super.clone(values, options); + } +}`, + `${imports}class MyNote extends Note { + override ["clone"](values = {}, options = {}) { + void this.clone().getObject(); + return super.clone(values, options); + } +}`, + `${imports}class MyNote extends Note { + override deepClone(values = {}, options = {}) { + const copy = this.clone(); + void copy.getAttachments(); + return super.deepClone(values, options); + } +}`, + `${imports}class MyNote extends Note { + override deepClone(values = {}, options = {}) { + const self = this; + void self.clone().getAttachments(); + return super.deepClone(values, options); + } +}`, + `${imports}class MyNote extends Note { + override clone = (values = {}, options = {}) => { + void super.clone().getAttachments(); + return super.clone(values, options); + }; +}`, + ]) { + const [message] = verify(code); + assert.equal(message.messageId, "dropsVerifier"); + assert.equal(message.suggestions, undefined); + } +}); + +test("ESLint: re-cloned copies report the first clone without a suggestion", () => { + for (const body of [ + "await c.getObject();\n await c.clone().getObject();", + "await c.clone().getObject();\n await c.getObject();", + ]) { + const code = `${imports}async function f(note: Note) { + const c = note.clone(); + ${body} +}`; + const messages = verify(code); + assert.equal(messages.length, 1, body); + assert.equal(messages[0].messageId, "dropsVerifierRechained"); + assert.equal(messages[0].line, 3); + assert.equal(messages[0].suggestions, undefined); + } +}); + +test("ESLint: modules option adds other vocabulary modules", () => { + const code = `import { Note } from "@example/vocab"; +async function f(note: Note) { await note.clone().getObject(); }`; + assert.equal(verify(code).length, 0); + assert.equal(verify(code, { modules: ["@example/vocab"] }).length, 1); + // lookupObject() is recognized only from Fedify's own module: + assert.equal( + verify( + `import { lookupObject } from "@example/vocab"; +async function f(ctx: never) { await (await lookupObject("x", ctx))?.clone().getObject(); }`, + { modules: ["@example/vocab"] }, + ).length, + 0, + ); +}); + +const OXLINT_BAD = `import type { Object as APObject } from "@fedify/vocab"; +import { Note } from "@fedify/vocab"; + +export async function a(note: APObject | null) { + return await (note as APObject)?.clone().getContextHistory({ + crossOrigin: "trust", + }); +} + +export async function b(note: Note) { + const copy = note.clone(); + return await copy.getObject(); +} + +export async function c(note: Note) { + return await note.clone({}, note as never).getObject(); +} +`; + +test("Oxlint: reports dropped verifiers", { skip: oxlintUnavailable }, () => { + const { diagnostics, stdout, stderr } = runOxlint(OXLINT_BAD, { + rules: { [`@fedify/lint/${ruleName}`]: "warn" }, + }); + const ours = diagnostics.filter((d) => d.code?.includes(ruleName)); + assert.equal(ours.length, 2, `stdout: ${stdout}\nstderr: ${stderr}`); + assert.ok(ours.every((d) => d.message?.includes(reported))); +}); + +test("Oxlint: stays quiet unless enabled", { skip: oxlintUnavailable }, () => { + const { diagnostics } = runOxlint(OXLINT_BAD, { rules: {} }); + assert.equal(diagnostics.filter((d) => d.code?.includes(ruleName)).length, 0); +}); From ba0f4ba5eb88a516fceb421a7a9d7d2835d0c7e8 Mon Sep 17 00:00:00 2001 From: Hong Minhee Date: Sun, 15 Nov 2026 15:11:09 +0900 Subject: [PATCH 2/2] Track for-await loops over aliased accessor results vocab-clone-verifier only recognized a for-await binding as a vocabulary object when the loop iterated an accessor call directly. Saving the iterable first, as in "const objects = create.getObjects()", left the binding unknown, so the rule missed a clone() inside the loop. The iterated expression is now resolved through the initializers of variables that are never reassigned before it is checked for an accessor call. A reassigned alias stays unknown. https://github.com/fedify-dev/fedify/pull/1443#discussion_r4575522083 Changelog: none Assisted-by: Claude Code:claude-opus-5-5 --- packages/lint/src/lib/vocab-clone.ts | 26 ++++++++++++++++++- .../src/tests/vocab-clone-verifier.test.ts | 21 +++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/packages/lint/src/lib/vocab-clone.ts b/packages/lint/src/lib/vocab-clone.ts index fe6336993..8b0b171ca 100644 --- a/packages/lint/src/lib/vocab-clone.ts +++ b/packages/lint/src/lib/vocab-clone.ts @@ -765,7 +765,7 @@ export function checkVocabClones( if (binding.kind === "variable") { if (binding.init) state = evaluate(binding.init); if (state.kind === "unknown" && binding.iterated) { - const iterated = unwrapValue(binding.iterated); + const iterated = resolveAlias(binding.iterated); if (iterated?.type === "CallExpression" && isAccessorCall(iterated)) { state = evaluate(iterated); } @@ -787,6 +787,30 @@ export function checkVocabClones( return state; } + /** + * Follows identifiers through the initializers of variables that are never + * reassigned, so `const objects = create.getObjects()` iterated later still + * resolves to the accessor call. + */ + function resolveAlias(expression: Ast): Ast | undefined { + let node = unwrapValue(expression); + const seen = new Set(); + while (node?.type === "Identifier") { + const binding = lookup(scopes.get(node), node.name as string); + if ( + binding?.kind !== "variable" || + binding.opaque || + binding.init == null || + seen.has(binding) + ) { + break; + } + seen.add(binding); + node = unwrapValue(binding.init); + } + return node; + } + function isAccessorCall(call: Ast): boolean { const callee = unwrapValue(ast(call.callee)); if (callee?.type !== "MemberExpression") return false; diff --git a/packages/lint/src/tests/vocab-clone-verifier.test.ts b/packages/lint/src/tests/vocab-clone-verifier.test.ts index 06b4715e5..a85e37c1b 100644 --- a/packages/lint/src/tests/vocab-clone-verifier.test.ts +++ b/packages/lint/src/tests/vocab-clone-verifier.test.ts @@ -191,6 +191,27 @@ const cases: [string, string, string?][] = [ }`, reported, ], + [ + "for-await binding over an aliased accessor result", + `${imports}async function f(create: Create) { + const objects = create.getObjects(); + const items = objects; + for await (const object of items) { + await object.clone().getAttribution(); + } + }`, + reported, + ], + [ + "for-await binding over a reassigned alias", + `${imports}async function f(create: Create, other: AsyncIterable) { + let objects = create.getObjects(); + objects = other; + for await (const object of objects) { + await object.clone().getAttribution(); + } + }`, + ], [ "unconsumed plural accessor", `${imports}async function f(note: Note) {