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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand All @@ -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

Expand Down
16 changes: 16 additions & 0 deletions changes.d/lint/vocab-clone-verifier.md
Original file line number Diff line number Diff line change
@@ -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]]
4 changes: 4 additions & 0 deletions claude-plugin/skills/fedify/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
123 changes: 123 additions & 0 deletions docs/manual/lint.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/
Expand Down Expand Up @@ -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<void>, 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
Expand Down
7 changes: 7 additions & 0 deletions packages/lint/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
2 changes: 2 additions & 0 deletions packages/lint/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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> =
{
Expand Down Expand Up @@ -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)[] = [
Expand Down
124 changes: 124 additions & 0 deletions packages/lint/src/lib/ast.ts
Original file line number Diff line number Diff line change
@@ -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<string> = 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)
);
}
3 changes: 3 additions & 0 deletions packages/lint/src/lib/const.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
13 changes: 13 additions & 0 deletions packages/lint/src/lib/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
};
Loading
Loading